Merge branch 'MDL-74441-400' of https://github.com/cameron1729/moodle into MOODLE_400...
[moodle.git] / mod / assign / lib.php
blobabd2c77f4f9e8fe3b29cd974edd649302a4be1c1
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 require_once(__DIR__ . '/deprecatedlib.php');
30 /**
31 * Adds an assignment instance
33 * This is done by calling the add_instance() method of the assignment type class
34 * @param stdClass $data
35 * @param mod_assign_mod_form $form
36 * @return int The instance id of the new assignment
38 function assign_add_instance(stdClass $data, mod_assign_mod_form $form = null) {
39 global $CFG;
40 require_once($CFG->dirroot . '/mod/assign/locallib.php');
42 $assignment = new assign(context_module::instance($data->coursemodule), null, null);
43 return $assignment->add_instance($data, true);
46 /**
47 * delete an assignment instance
48 * @param int $id
49 * @return bool
51 function assign_delete_instance($id) {
52 global $CFG;
53 require_once($CFG->dirroot . '/mod/assign/locallib.php');
54 $cm = get_coursemodule_from_instance('assign', $id, 0, false, MUST_EXIST);
55 $context = context_module::instance($cm->id);
57 $assignment = new assign($context, null, null);
58 return $assignment->delete_instance();
61 /**
62 * This function is used by the reset_course_userdata function in moodlelib.
63 * This function will remove all assignment submissions and feedbacks in the database
64 * and clean up any related data.
66 * @param stdClass $data the data submitted from the reset course.
67 * @return array
69 function assign_reset_userdata($data) {
70 global $CFG, $DB;
71 require_once($CFG->dirroot . '/mod/assign/locallib.php');
73 $status = array();
74 $params = array('courseid'=>$data->courseid);
75 $sql = "SELECT a.id FROM {assign} a WHERE a.course=:courseid";
76 $course = $DB->get_record('course', array('id'=>$data->courseid), '*', MUST_EXIST);
77 if ($assigns = $DB->get_records_sql($sql, $params)) {
78 foreach ($assigns as $assign) {
79 $cm = get_coursemodule_from_instance('assign',
80 $assign->id,
81 $data->courseid,
82 false,
83 MUST_EXIST);
84 $context = context_module::instance($cm->id);
85 $assignment = new assign($context, $cm, $course);
86 $status = array_merge($status, $assignment->reset_userdata($data));
89 return $status;
92 /**
93 * This standard function will check all instances of this module
94 * and make sure there are up-to-date events created for each of them.
95 * If courseid = 0, then every assignment event in the site is checked, else
96 * only assignment events belonging to the course specified are checked.
98 * @param int $courseid
99 * @param int|stdClass $instance Assign module instance or ID.
100 * @param int|stdClass $cm Course module object or ID (not used in this module).
101 * @return bool
103 function assign_refresh_events($courseid = 0, $instance = null, $cm = null) {
104 global $CFG, $DB;
105 require_once($CFG->dirroot . '/mod/assign/locallib.php');
107 // If we have instance information then we can just update the one event instead of updating all events.
108 if (isset($instance)) {
109 if (!is_object($instance)) {
110 $instance = $DB->get_record('assign', array('id' => $instance), '*', MUST_EXIST);
112 if (isset($cm)) {
113 if (!is_object($cm)) {
114 assign_prepare_update_events($instance);
115 return true;
116 } else {
117 $course = get_course($instance->course);
118 assign_prepare_update_events($instance, $course, $cm);
119 return true;
124 if ($courseid) {
125 // Make sure that the course id is numeric.
126 if (!is_numeric($courseid)) {
127 return false;
129 if (!$assigns = $DB->get_records('assign', array('course' => $courseid))) {
130 return false;
132 // Get course from courseid parameter.
133 if (!$course = $DB->get_record('course', array('id' => $courseid), '*')) {
134 return false;
136 } else {
137 if (!$assigns = $DB->get_records('assign')) {
138 return false;
141 foreach ($assigns as $assign) {
142 assign_prepare_update_events($assign);
145 return true;
149 * This actually updates the normal and completion calendar events.
151 * @param stdClass $assign Assignment object (from DB).
152 * @param stdClass $course Course object.
153 * @param stdClass $cm Course module object.
155 function assign_prepare_update_events($assign, $course = null, $cm = null) {
156 global $DB;
157 if (!isset($course)) {
158 // Get course and course module for the assignment.
159 list($course, $cm) = get_course_and_cm_from_instance($assign->id, 'assign', $assign->course);
161 // Refresh the assignment's calendar events.
162 $context = context_module::instance($cm->id);
163 $assignment = new assign($context, $cm, $course);
164 $assignment->update_calendar($cm->id);
165 // Refresh the calendar events also for the assignment overrides.
166 $overrides = $DB->get_records('assign_overrides', ['assignid' => $assign->id], '',
167 'id, groupid, userid, duedate, sortorder, timelimit');
168 foreach ($overrides as $override) {
169 if (empty($override->userid)) {
170 unset($override->userid);
172 if (empty($override->groupid)) {
173 unset($override->groupid);
175 assign_update_events($assignment, $override);
180 * Removes all grades from gradebook
182 * @param int $courseid The ID of the course to reset
183 * @param string $type Optional type of assignment to limit the reset to a particular assignment type
185 function assign_reset_gradebook($courseid, $type='') {
186 global $CFG, $DB;
188 $params = array('moduletype'=>'assign', 'courseid'=>$courseid);
189 $sql = 'SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
190 FROM {assign} a, {course_modules} cm, {modules} m
191 WHERE m.name=:moduletype AND m.id=cm.module AND cm.instance=a.id AND a.course=:courseid';
193 if ($assignments = $DB->get_records_sql($sql, $params)) {
194 foreach ($assignments as $assignment) {
195 assign_grade_item_update($assignment, 'reset');
201 * Implementation of the function for printing the form elements that control
202 * whether the course reset functionality affects the assignment.
203 * @param moodleform $mform form passed by reference
205 function assign_reset_course_form_definition(&$mform) {
206 $mform->addElement('header', 'assignheader', get_string('modulenameplural', 'assign'));
207 $name = get_string('deleteallsubmissions', 'assign');
208 $mform->addElement('advcheckbox', 'reset_assign_submissions', $name);
209 $mform->addElement('advcheckbox', 'reset_assign_user_overrides',
210 get_string('removealluseroverrides', 'assign'));
211 $mform->addElement('advcheckbox', 'reset_assign_group_overrides',
212 get_string('removeallgroupoverrides', 'assign'));
216 * Course reset form defaults.
217 * @param object $course
218 * @return array
220 function assign_reset_course_form_defaults($course) {
221 return array('reset_assign_submissions' => 1,
222 'reset_assign_group_overrides' => 1,
223 'reset_assign_user_overrides' => 1);
227 * Update an assignment instance
229 * This is done by calling the update_instance() method of the assignment type class
230 * @param stdClass $data
231 * @param stdClass $form - unused
232 * @return object
234 function assign_update_instance(stdClass $data, $form) {
235 global $CFG;
236 require_once($CFG->dirroot . '/mod/assign/locallib.php');
237 $context = context_module::instance($data->coursemodule);
238 $assignment = new assign($context, null, null);
239 return $assignment->update_instance($data);
243 * This function updates the events associated to the assign.
244 * If $override is non-zero, then it updates only the events
245 * associated with the specified override.
247 * @param assign $assign the assign object.
248 * @param object $override (optional) limit to a specific override
250 function assign_update_events($assign, $override = null) {
251 global $CFG, $DB;
253 require_once($CFG->dirroot . '/calendar/lib.php');
255 $assigninstance = $assign->get_instance();
257 // Load the old events relating to this assign.
258 $conds = array('modulename' => 'assign', 'instance' => $assigninstance->id);
259 if (!empty($override)) {
260 // Only load events for this override.
261 if (isset($override->userid)) {
262 $conds['userid'] = $override->userid;
263 } else if (isset($override->groupid)) {
264 $conds['groupid'] = $override->groupid;
265 } else {
266 // This is not a valid override, it may have been left from a bad import or restore.
267 $conds['groupid'] = $conds['userid'] = 0;
270 $oldevents = $DB->get_records('event', $conds, 'id ASC');
272 // Now make a to-do list of all that needs to be updated.
273 if (empty($override)) {
274 // We are updating the primary settings for the assignment, so we need to add all the overrides.
275 $overrides = $DB->get_records('assign_overrides', array('assignid' => $assigninstance->id), 'id ASC');
276 // It is necessary to add an empty stdClass to the beginning of the array as the $oldevents
277 // list contains the original (non-override) event for the module. If this is not included
278 // the logic below will end up updating the wrong row when we try to reconcile this $overrides
279 // list against the $oldevents list.
280 array_unshift($overrides, new stdClass());
281 } else {
282 // Just do the one override.
283 $overrides = array($override);
286 if (!empty($assign->get_course_module())) {
287 $cmid = $assign->get_course_module()->id;
288 } else {
289 $cmid = get_coursemodule_from_instance('assign', $assigninstance->id, $assigninstance->course)->id;
292 foreach ($overrides as $current) {
293 $groupid = isset($current->groupid) ? $current->groupid : 0;
294 $userid = isset($current->userid) ? $current->userid : 0;
295 $duedate = isset($current->duedate) ? $current->duedate : $assigninstance->duedate;
296 $timelimit = isset($current->timelimit) ? $current->timelimit : 0;
298 // Only add 'due' events for an override if they differ from the assign default.
299 $addclose = empty($current->id) || !empty($current->duedate);
301 $event = new stdClass();
302 $event->type = CALENDAR_EVENT_TYPE_ACTION;
303 $event->description = format_module_intro('assign', $assigninstance, $cmid, false);
304 $event->format = FORMAT_HTML;
305 // Events module won't show user events when the courseid is nonzero.
306 $event->courseid = ($userid) ? 0 : $assigninstance->course;
307 $event->groupid = $groupid;
308 $event->userid = $userid;
309 $event->modulename = 'assign';
310 $event->instance = $assigninstance->id;
311 $event->timestart = $duedate;
312 $event->timeduration = $timelimit;
313 $event->timesort = $event->timestart + $event->timeduration;
314 $event->visible = instance_is_visible('assign', $assigninstance);
315 $event->eventtype = ASSIGN_EVENT_TYPE_DUE;
316 $event->priority = null;
318 // Determine the event name and priority.
319 if ($groupid) {
320 // Group override event.
321 $params = new stdClass();
322 $params->assign = $assigninstance->name;
323 $params->group = groups_get_group_name($groupid);
324 if ($params->group === false) {
325 // Group doesn't exist, just skip it.
326 continue;
328 $eventname = get_string('overridegroupeventname', 'assign', $params);
329 // Set group override priority.
330 if (isset($current->sortorder)) {
331 $event->priority = $current->sortorder;
333 } else if ($userid) {
334 // User override event.
335 $params = new stdClass();
336 $params->assign = $assigninstance->name;
337 $eventname = get_string('overrideusereventname', 'assign', $params);
338 // Set user override priority.
339 $event->priority = CALENDAR_EVENT_USER_OVERRIDE_PRIORITY;
340 } else {
341 // The parent event.
342 $eventname = $assigninstance->name;
345 if ($duedate && $addclose) {
346 if ($oldevent = array_shift($oldevents)) {
347 $event->id = $oldevent->id;
348 } else {
349 unset($event->id);
351 $event->name = $eventname.' ('.get_string('duedate', 'assign').')';
352 calendar_event::create($event, false);
356 // Delete any leftover events.
357 foreach ($oldevents as $badevent) {
358 $badevent = calendar_event::load($badevent);
359 $badevent->delete();
364 * Return the list if Moodle features this module supports
366 * @param string $feature FEATURE_xx constant for requested feature
367 * @return mixed True if module supports feature, false if not, null if doesn't know or string for the module purpose.
369 function assign_supports($feature) {
370 switch($feature) {
371 case FEATURE_GROUPS:
372 return true;
373 case FEATURE_GROUPINGS:
374 return true;
375 case FEATURE_MOD_INTRO:
376 return true;
377 case FEATURE_COMPLETION_TRACKS_VIEWS:
378 return true;
379 case FEATURE_COMPLETION_HAS_RULES:
380 return true;
381 case FEATURE_GRADE_HAS_GRADE:
382 return true;
383 case FEATURE_GRADE_OUTCOMES:
384 return true;
385 case FEATURE_BACKUP_MOODLE2:
386 return true;
387 case FEATURE_SHOW_DESCRIPTION:
388 return true;
389 case FEATURE_ADVANCED_GRADING:
390 return true;
391 case FEATURE_PLAGIARISM:
392 return true;
393 case FEATURE_COMMENT:
394 return true;
395 case FEATURE_MOD_PURPOSE:
396 return MOD_PURPOSE_ASSESSMENT;
398 default:
399 return null;
404 * extend an assigment navigation settings
406 * @param settings_navigation $settings
407 * @param navigation_node $navref
408 * @return void
410 function assign_extend_settings_navigation(settings_navigation $settings, navigation_node $navref) {
411 global $DB;
413 // We want to add these new nodes after the Edit settings node, and before the
414 // Locally assigned roles node. Of course, both of those are controlled by capabilities.
415 $keys = $navref->get_children_key_list();
416 $beforekey = null;
417 $i = array_search('modedit', $keys);
418 if ($i === false and array_key_exists(0, $keys)) {
419 $beforekey = $keys[0];
420 } else if (array_key_exists($i + 1, $keys)) {
421 $beforekey = $keys[$i + 1];
424 $cm = $settings->get_page()->cm;
425 if (!$cm) {
426 return;
429 $context = $cm->context;
430 $course = $settings->get_page()->course;
432 if (!$course) {
433 return;
436 if (has_capability('mod/assign:manageoverrides', $settings->get_page()->cm->context)) {
437 $url = new moodle_url('/mod/assign/overrides.php', ['cmid' => $settings->get_page()->cm->id, 'mode' => 'user']);
439 $node = navigation_node::create(get_string('overrides', 'assign'),
440 $url,
441 navigation_node::TYPE_SETTING, null, 'mod_assign_useroverrides');
442 $navref->add_node($node, $beforekey);
445 if (has_capability('mod/assign:revealidentities', $context)) {
446 $dbparams = array('id'=>$cm->instance);
447 $assignment = $DB->get_record('assign', $dbparams, 'blindmarking, revealidentities');
449 if ($assignment && $assignment->blindmarking && !$assignment->revealidentities) {
450 $urlparams = array('id' => $cm->id, 'action'=>'revealidentities');
451 $url = new moodle_url('/mod/assign/view.php', $urlparams);
452 $linkname = get_string('revealidentities', 'assign');
453 $node = $navref->add($linkname, $url, navigation_node::TYPE_SETTING);
459 * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
460 * for the course (see resource).
462 * Given a course_module object, this function returns any "extra" information that may be needed
463 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
465 * @param stdClass $coursemodule The coursemodule object (record).
466 * @return cached_cm_info An object on information that the courses
467 * will know about (most noticeably, an icon).
469 function assign_get_coursemodule_info($coursemodule) {
470 global $DB;
472 $dbparams = array('id'=>$coursemodule->instance);
473 $fields = 'id, name, alwaysshowdescription, allowsubmissionsfromdate, intro, introformat, completionsubmit,
474 duedate, cutoffdate, allowsubmissionsfromdate';
475 if (! $assignment = $DB->get_record('assign', $dbparams, $fields)) {
476 return false;
479 $result = new cached_cm_info();
480 $result->name = $assignment->name;
481 if ($coursemodule->showdescription) {
482 if ($assignment->alwaysshowdescription || time() > $assignment->allowsubmissionsfromdate) {
483 // Convert intro to html. Do not filter cached version, filters run at display time.
484 $result->content = format_module_intro('assign', $assignment, $coursemodule->id, false);
488 // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
489 if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) {
490 $result->customdata['customcompletionrules']['completionsubmit'] = $assignment->completionsubmit;
493 // Populate some other values that can be used in calendar or on dashboard.
494 if ($assignment->duedate) {
495 $result->customdata['duedate'] = $assignment->duedate;
497 if ($assignment->cutoffdate) {
498 $result->customdata['cutoffdate'] = $assignment->cutoffdate;
500 if ($assignment->allowsubmissionsfromdate) {
501 $result->customdata['allowsubmissionsfromdate'] = $assignment->allowsubmissionsfromdate;
504 return $result;
508 * Sets dynamic information about a course module
510 * This function is called from cm_info when displaying the module
512 * @param cm_info $cm
514 function mod_assign_cm_info_dynamic(cm_info $cm) {
515 global $USER;
517 $cache = cache::make('mod_assign', 'overrides');
518 $override = $cache->get("{$cm->instance}_u_{$USER->id}");
520 if (!$override) {
521 $override = (object) [
522 'allowsubmissionsfromdate' => null,
523 'duedate' => null,
524 'cutoffdate' => null,
528 // No need to look for group overrides if there are user overrides for all allowsubmissionsfromdate, duedate and cutoffdate.
529 if (is_null($override->allowsubmissionsfromdate) || is_null($override->duedate) || is_null($override->cutoffdate)) {
530 $selectedgroupoverride = (object) [
531 'allowsubmissionsfromdate' => null,
532 'duedate' => null,
533 'cutoffdate' => null,
534 'sortorder' => PHP_INT_MAX, // So that every sortorder read from DB is less than this.
536 $groupings = groups_get_user_groups($cm->course, $USER->id);
537 foreach ($groupings[0] as $groupid) {
538 $groupoverride = $cache->get("{$cm->instance}_g_{$groupid}");
539 if ($groupoverride) {
540 if ($groupoverride->sortorder < $selectedgroupoverride->sortorder) {
541 $selectedgroupoverride = $groupoverride;
545 // If there is a user override for a setting, ignore the group override.
546 if (is_null($override->allowsubmissionsfromdate)) {
547 $override->allowsubmissionsfromdate = $selectedgroupoverride->allowsubmissionsfromdate;
549 if (is_null($override->duedate)) {
550 $override->duedate = $selectedgroupoverride->duedate;
552 if (is_null($override->cutoffdate)) {
553 $override->cutoffdate = $selectedgroupoverride->cutoffdate;
557 // Calculate relative dates. The assignment module calculates relative date only for duedate.
558 // A user or group override always has higher priority over any relative date calculation.
559 if (empty($override->duedate) && !empty($cm->customdata['duedate'])) {
560 $course = get_course($cm->course);
561 $usercoursedates = course_get_course_dates_for_user_id($course, $USER->id);
562 if ($usercoursedates['start']) {
563 $override->duedate = $cm->customdata['duedate'] + $usercoursedates['startoffset'];
567 // Populate some other values that can be used in calendar or on dashboard.
568 if (!is_null($override->allowsubmissionsfromdate)) {
569 $cm->override_customdata('allowsubmissionsfromdate', $override->allowsubmissionsfromdate);
571 if (!is_null($override->duedate)) {
572 $cm->override_customdata('duedate', $override->duedate);
574 if (!is_null($override->cutoffdate)) {
575 $cm->override_customdata('cutoffdate', $override->cutoffdate);
580 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
582 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
583 * @return array $descriptions the array of descriptions for the custom rules.
585 function mod_assign_get_completion_active_rule_descriptions($cm) {
586 // Values will be present in cm_info, and we assume these are up to date.
587 if (empty($cm->customdata['customcompletionrules'])
588 || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
589 return [];
592 $descriptions = [];
593 foreach ($cm->customdata['customcompletionrules'] as $key => $val) {
594 switch ($key) {
595 case 'completionsubmit':
596 if (!empty($val)) {
597 $descriptions[] = get_string('completionsubmit', 'assign');
599 break;
600 default:
601 break;
604 return $descriptions;
608 * Return a list of page types
609 * @param string $pagetype current page type
610 * @param stdClass $parentcontext Block's parent context
611 * @param stdClass $currentcontext Current context of block
613 function assign_page_type_list($pagetype, $parentcontext, $currentcontext) {
614 $modulepagetype = array(
615 'mod-assign-*' => get_string('page-mod-assign-x', 'assign'),
616 'mod-assign-view' => get_string('page-mod-assign-view', 'assign'),
618 return $modulepagetype;
622 * @deprecated since Moodle 3.3, when the block_course_overview block was removed.
624 function assign_print_overview() {
625 throw new coding_exception('assign_print_overview() can not be used any more and is obsolete.');
629 * @deprecated since Moodle 3.3, when the block_course_overview block was removed.
631 function assign_get_mysubmission_details_for_print_overview() {
632 throw new coding_exception('assign_get_mysubmission_details_for_print_overview() can not be used any more and is obsolete.');
636 * @deprecated since Moodle 3.3, when the block_course_overview block was removed.
638 function assign_get_grade_details_for_print_overview() {
639 throw new coding_exception('assign_get_grade_details_for_print_overview() can not be used any more and is obsolete.');
643 * Print recent activity from all assignments in a given course
645 * This is used by the recent activity block
646 * @param mixed $course the course to print activity for
647 * @param bool $viewfullnames boolean to determine whether to show full names or not
648 * @param int $timestart the time the rendering started
649 * @return bool true if activity was printed, false otherwise.
651 function assign_print_recent_activity($course, $viewfullnames, $timestart) {
652 global $CFG, $USER, $DB, $OUTPUT;
653 require_once($CFG->dirroot . '/mod/assign/locallib.php');
655 // Do not use log table if possible, it may be huge.
657 $dbparams = array($timestart, $course->id, 'assign', ASSIGN_SUBMISSION_STATUS_SUBMITTED);
658 $userfieldsapi = \core_user\fields::for_userpic();
659 $namefields = $userfieldsapi->get_sql('u', false, '', 'userid', false)->selects;;
660 if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, um.id as recordid,
661 $namefields
662 FROM {assign_submission} asb
663 JOIN {assign} a ON a.id = asb.assignment
664 JOIN {course_modules} cm ON cm.instance = a.id
665 JOIN {modules} md ON md.id = cm.module
666 JOIN {user} u ON u.id = asb.userid
667 LEFT JOIN {assign_user_mapping} um ON um.userid = u.id AND um.assignment = a.id
668 WHERE asb.timemodified > ? AND
669 asb.latest = 1 AND
670 a.course = ? AND
671 md.name = ? AND
672 asb.status = ?
673 ORDER BY asb.timemodified ASC", $dbparams)) {
674 return false;
677 $modinfo = get_fast_modinfo($course);
678 $show = array();
679 $grader = array();
681 $showrecentsubmissions = get_config('assign', 'showrecentsubmissions');
683 foreach ($submissions as $submission) {
684 if (!array_key_exists($submission->cmid, $modinfo->get_cms())) {
685 continue;
687 $cm = $modinfo->get_cm($submission->cmid);
688 if (!$cm->uservisible) {
689 continue;
691 if ($submission->userid == $USER->id) {
692 $show[] = $submission;
693 continue;
696 $context = context_module::instance($submission->cmid);
697 // The act of submitting of assignment may be considered private -
698 // only graders will see it if specified.
699 if (empty($showrecentsubmissions)) {
700 if (!array_key_exists($cm->id, $grader)) {
701 $grader[$cm->id] = has_capability('moodle/grade:viewall', $context);
703 if (!$grader[$cm->id]) {
704 continue;
708 $groupmode = groups_get_activity_groupmode($cm, $course);
710 if ($groupmode == SEPARATEGROUPS &&
711 !has_capability('moodle/site:accessallgroups', $context)) {
712 if (isguestuser()) {
713 // Shortcut - guest user does not belong into any group.
714 continue;
717 // This will be slow - show only users that share group with me in this cm.
718 if (!$modinfo->get_groups($cm->groupingid)) {
719 continue;
721 $usersgroups = groups_get_all_groups($course->id, $submission->userid, $cm->groupingid);
722 if (is_array($usersgroups)) {
723 $usersgroups = array_keys($usersgroups);
724 $intersect = array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid));
725 if (empty($intersect)) {
726 continue;
730 $show[] = $submission;
733 if (empty($show)) {
734 return false;
737 echo $OUTPUT->heading(get_string('newsubmissions', 'assign') . ':', 6);
739 foreach ($show as $submission) {
740 $cm = $modinfo->get_cm($submission->cmid);
741 $context = context_module::instance($submission->cmid);
742 $assign = new assign($context, $cm, $cm->course);
743 $link = $CFG->wwwroot.'/mod/assign/view.php?id='.$cm->id;
744 // Obscure first and last name if blind marking enabled.
745 if ($assign->is_blind_marking()) {
746 $submission->firstname = get_string('participant', 'mod_assign');
747 if (empty($submission->recordid)) {
748 $submission->recordid = $assign->get_uniqueid_for_user($submission->userid);
750 $submission->lastname = $submission->recordid;
752 print_recent_activity_note($submission->timemodified,
753 $submission,
754 $cm->name,
755 $link,
756 false,
757 $viewfullnames);
760 return true;
764 * Returns all assignments since a given time.
766 * @param array $activities The activity information is returned in this array
767 * @param int $index The current index in the activities array
768 * @param int $timestart The earliest activity to show
769 * @param int $courseid Limit the search to this course
770 * @param int $cmid The course module id
771 * @param int $userid Optional user id
772 * @param int $groupid Optional group id
773 * @return void
775 function assign_get_recent_mod_activity(&$activities,
776 &$index,
777 $timestart,
778 $courseid,
779 $cmid,
780 $userid=0,
781 $groupid=0) {
782 global $CFG, $COURSE, $USER, $DB;
784 require_once($CFG->dirroot . '/mod/assign/locallib.php');
786 if ($COURSE->id == $courseid) {
787 $course = $COURSE;
788 } else {
789 $course = $DB->get_record('course', array('id'=>$courseid));
792 $modinfo = get_fast_modinfo($course);
794 $cm = $modinfo->get_cm($cmid);
795 $params = array();
796 if ($userid) {
797 $userselect = 'AND u.id = :userid';
798 $params['userid'] = $userid;
799 } else {
800 $userselect = '';
803 if ($groupid) {
804 $groupselect = 'AND gm.groupid = :groupid';
805 $groupjoin = 'JOIN {groups_members} gm ON gm.userid=u.id';
806 $params['groupid'] = $groupid;
807 } else {
808 $groupselect = '';
809 $groupjoin = '';
812 $params['cminstance'] = $cm->instance;
813 $params['timestart'] = $timestart;
814 $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
816 $userfieldsapi = \core_user\fields::for_userpic();
817 $userfields = $userfieldsapi->get_sql('u', false, '', 'userid', false)->selects;
819 if (!$submissions = $DB->get_records_sql('SELECT asb.id, asb.timemodified, ' .
820 $userfields .
821 ' FROM {assign_submission} asb
822 JOIN {assign} a ON a.id = asb.assignment
823 JOIN {user} u ON u.id = asb.userid ' .
824 $groupjoin .
825 ' WHERE asb.timemodified > :timestart AND
826 asb.status = :submitted AND
827 a.id = :cminstance
828 ' . $userselect . ' ' . $groupselect .
829 ' ORDER BY asb.timemodified ASC', $params)) {
830 return;
833 $groupmode = groups_get_activity_groupmode($cm, $course);
834 $cmcontext = context_module::instance($cm->id);
835 $grader = has_capability('moodle/grade:viewall', $cmcontext);
836 $accessallgroups = has_capability('moodle/site:accessallgroups', $cmcontext);
837 $viewfullnames = has_capability('moodle/site:viewfullnames', $cmcontext);
840 $showrecentsubmissions = get_config('assign', 'showrecentsubmissions');
841 $show = array();
842 foreach ($submissions as $submission) {
843 if ($submission->userid == $USER->id) {
844 $show[] = $submission;
845 continue;
847 // The act of submitting of assignment may be considered private -
848 // only graders will see it if specified.
849 if (empty($showrecentsubmissions)) {
850 if (!$grader) {
851 continue;
855 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
856 if (isguestuser()) {
857 // Shortcut - guest user does not belong into any group.
858 continue;
861 // This will be slow - show only users that share group with me in this cm.
862 if (!$modinfo->get_groups($cm->groupingid)) {
863 continue;
865 $usersgroups = groups_get_all_groups($course->id, $submission->userid, $cm->groupingid);
866 if (is_array($usersgroups)) {
867 $usersgroups = array_keys($usersgroups);
868 $intersect = array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid));
869 if (empty($intersect)) {
870 continue;
874 $show[] = $submission;
877 if (empty($show)) {
878 return;
881 if ($grader) {
882 require_once($CFG->libdir.'/gradelib.php');
883 $userids = array();
884 foreach ($show as $id => $submission) {
885 $userids[] = $submission->userid;
887 $grades = grade_get_grades($courseid, 'mod', 'assign', $cm->instance, $userids);
890 $aname = format_string($cm->name, true);
891 foreach ($show as $submission) {
892 $activity = new stdClass();
894 $activity->type = 'assign';
895 $activity->cmid = $cm->id;
896 $activity->name = $aname;
897 $activity->sectionnum = $cm->sectionnum;
898 $activity->timestamp = $submission->timemodified;
899 $activity->user = new stdClass();
900 if ($grader) {
901 $activity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
904 $userfields = explode(',', implode(',', \core_user\fields::get_picture_fields()));
905 foreach ($userfields as $userfield) {
906 if ($userfield == 'id') {
907 // Aliased in SQL above.
908 $activity->user->{$userfield} = $submission->userid;
909 } else {
910 $activity->user->{$userfield} = $submission->{$userfield};
913 $activity->user->fullname = fullname($submission, $viewfullnames);
915 $activities[$index++] = $activity;
918 return;
922 * Print recent activity from all assignments in a given course
924 * This is used by course/recent.php
925 * @param stdClass $activity
926 * @param int $courseid
927 * @param bool $detail
928 * @param array $modnames
930 function assign_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
931 global $CFG, $OUTPUT;
933 echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
935 echo '<tr><td class="userpicture" valign="top">';
936 echo $OUTPUT->user_picture($activity->user);
937 echo '</td><td>';
939 if ($detail) {
940 $modname = $modnames[$activity->type];
941 echo '<div class="title">';
942 echo $OUTPUT->image_icon('monologo', $modname, 'assign');
943 echo '<a href="' . $CFG->wwwroot . '/mod/assign/view.php?id=' . $activity->cmid . '">';
944 echo $activity->name;
945 echo '</a>';
946 echo '</div>';
949 if (isset($activity->grade)) {
950 echo '<div class="grade">';
951 echo get_string('gradenoun') . ': ';
952 echo $activity->grade;
953 echo '</div>';
956 echo '<div class="user">';
957 echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->id}&amp;course=$courseid\">";
958 echo "{$activity->user->fullname}</a> - " . userdate($activity->timestamp);
959 echo '</div>';
961 echo '</td></tr></table>';
965 * @deprecated since Moodle 3.8
967 function assign_scale_used() {
968 throw new coding_exception('assign_scale_used() can not be used anymore. Plugins can implement ' .
969 '<modname>_scale_used_anywhere, all implementations of <modname>_scale_used are now ignored');
973 * Checks if scale is being used by any instance of assignment
975 * This is used to find out if scale used anywhere
976 * @param int $scaleid
977 * @return boolean True if the scale is used by any assignment
979 function assign_scale_used_anywhere($scaleid) {
980 global $DB;
982 if ($scaleid and $DB->record_exists('assign', array('grade'=>-$scaleid))) {
983 return true;
984 } else {
985 return false;
990 * List the actions that correspond to a view of this module.
991 * This is used by the participation report.
993 * Note: This is not used by new logging system. Event with
994 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
995 * be considered as view action.
997 * @return array
999 function assign_get_view_actions() {
1000 return array('view submission', 'view feedback');
1004 * List the actions that correspond to a post of this module.
1005 * This is used by the participation report.
1007 * Note: This is not used by new logging system. Event with
1008 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
1009 * will be considered as post action.
1011 * @return array
1013 function assign_get_post_actions() {
1014 return array('upload', 'submit', 'submit for grading');
1018 * Returns all other capabilities used by this module.
1019 * @return array Array of capability strings
1021 function assign_get_extra_capabilities() {
1022 return ['gradereport/grader:view', 'moodle/grade:viewall'];
1026 * Create grade item for given assignment.
1028 * @param stdClass $assign record with extra cmidnumber
1029 * @param array $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
1030 * @return int 0 if ok, error code otherwise
1032 function assign_grade_item_update($assign, $grades=null) {
1033 global $CFG;
1034 require_once($CFG->libdir.'/gradelib.php');
1036 if (!isset($assign->courseid)) {
1037 $assign->courseid = $assign->course;
1040 $params = array('itemname'=>$assign->name, 'idnumber'=>$assign->cmidnumber);
1042 // Check if feedback plugin for gradebook is enabled, if yes then
1043 // gradetype = GRADE_TYPE_TEXT else GRADE_TYPE_NONE.
1044 $gradefeedbackenabled = false;
1046 if (isset($assign->gradefeedbackenabled)) {
1047 $gradefeedbackenabled = $assign->gradefeedbackenabled;
1048 } else if ($assign->grade == 0) { // Grade feedback is needed only when grade == 0.
1049 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1050 $mod = get_coursemodule_from_instance('assign', $assign->id, $assign->courseid);
1051 $cm = context_module::instance($mod->id);
1052 $assignment = new assign($cm, null, null);
1053 $gradefeedbackenabled = $assignment->is_gradebook_feedback_enabled();
1056 if ($assign->grade > 0) {
1057 $params['gradetype'] = GRADE_TYPE_VALUE;
1058 $params['grademax'] = $assign->grade;
1059 $params['grademin'] = 0;
1061 } else if ($assign->grade < 0) {
1062 $params['gradetype'] = GRADE_TYPE_SCALE;
1063 $params['scaleid'] = -$assign->grade;
1065 } else if ($gradefeedbackenabled) {
1066 // $assign->grade == 0 and feedback enabled.
1067 $params['gradetype'] = GRADE_TYPE_TEXT;
1068 } else {
1069 // $assign->grade == 0 and no feedback enabled.
1070 $params['gradetype'] = GRADE_TYPE_NONE;
1073 if ($grades === 'reset') {
1074 $params['reset'] = true;
1075 $grades = null;
1078 return grade_update('mod/assign',
1079 $assign->courseid,
1080 'mod',
1081 'assign',
1082 $assign->id,
1084 $grades,
1085 $params);
1089 * Return grade for given user or all users.
1091 * @param stdClass $assign record of assign with an additional cmidnumber
1092 * @param int $userid optional user id, 0 means all users
1093 * @return array array of grades, false if none
1095 function assign_get_user_grades($assign, $userid=0) {
1096 global $CFG;
1098 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1100 $cm = get_coursemodule_from_instance('assign', $assign->id, 0, false, MUST_EXIST);
1101 $context = context_module::instance($cm->id);
1102 $assignment = new assign($context, null, null);
1103 $assignment->set_instance($assign);
1104 return $assignment->get_user_grades_for_gradebook($userid);
1108 * Update activity grades.
1110 * @param stdClass $assign database record
1111 * @param int $userid specific user only, 0 means all
1112 * @param bool $nullifnone - not used
1114 function assign_update_grades($assign, $userid=0, $nullifnone=true) {
1115 global $CFG;
1116 require_once($CFG->libdir.'/gradelib.php');
1118 if ($assign->grade == 0) {
1119 assign_grade_item_update($assign);
1121 } else if ($grades = assign_get_user_grades($assign, $userid)) {
1122 foreach ($grades as $k => $v) {
1123 if ($v->rawgrade == -1) {
1124 $grades[$k]->rawgrade = null;
1127 assign_grade_item_update($assign, $grades);
1129 } else {
1130 assign_grade_item_update($assign);
1135 * List the file areas that can be browsed.
1137 * @param stdClass $course
1138 * @param stdClass $cm
1139 * @param stdClass $context
1140 * @return array
1142 function assign_get_file_areas($course, $cm, $context) {
1143 global $CFG;
1144 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1146 $areas = array(
1147 ASSIGN_INTROATTACHMENT_FILEAREA => get_string('introattachments', 'mod_assign'),
1148 ASSIGN_ACTIVITYATTACHMENT_FILEAREA => get_string('activityattachments', 'mod_assign'),
1151 $assignment = new assign($context, $cm, $course);
1152 foreach ($assignment->get_submission_plugins() as $plugin) {
1153 if ($plugin->is_visible()) {
1154 $pluginareas = $plugin->get_file_areas();
1156 if ($pluginareas) {
1157 $areas = array_merge($areas, $pluginareas);
1161 foreach ($assignment->get_feedback_plugins() as $plugin) {
1162 if ($plugin->is_visible()) {
1163 $pluginareas = $plugin->get_file_areas();
1165 if ($pluginareas) {
1166 $areas = array_merge($areas, $pluginareas);
1171 return $areas;
1175 * File browsing support for assign module.
1177 * @param file_browser $browser
1178 * @param object $areas
1179 * @param object $course
1180 * @param object $cm
1181 * @param object $context
1182 * @param string $filearea
1183 * @param int $itemid
1184 * @param string $filepath
1185 * @param string $filename
1186 * @return object file_info instance or null if not found
1188 function assign_get_file_info($browser,
1189 $areas,
1190 $course,
1191 $cm,
1192 $context,
1193 $filearea,
1194 $itemid,
1195 $filepath,
1196 $filename) {
1197 global $CFG;
1198 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1200 if ($context->contextlevel != CONTEXT_MODULE) {
1201 return null;
1204 $urlbase = $CFG->wwwroot.'/pluginfile.php';
1205 $fs = get_file_storage();
1206 $filepath = is_null($filepath) ? '/' : $filepath;
1207 $filename = is_null($filename) ? '.' : $filename;
1209 // Need to find where this belongs to.
1210 $assignment = new assign($context, $cm, $course);
1211 if ($filearea === ASSIGN_INTROATTACHMENT_FILEAREA || $filearea === ASSIGN_ACTIVITYATTACHMENT_FILEAREA) {
1212 if (!has_capability('moodle/course:managefiles', $context)) {
1213 // Students can not peak here!
1214 return null;
1216 if (!($storedfile = $fs->get_file($assignment->get_context()->id,
1217 'mod_assign', $filearea, 0, $filepath, $filename))) {
1218 return null;
1220 return new file_info_stored($browser,
1221 $assignment->get_context(),
1222 $storedfile,
1223 $urlbase,
1224 $filearea,
1225 $itemid,
1226 true,
1227 true,
1228 false);
1231 $pluginowner = null;
1232 foreach ($assignment->get_submission_plugins() as $plugin) {
1233 if ($plugin->is_visible()) {
1234 $pluginareas = $plugin->get_file_areas();
1236 if (array_key_exists($filearea, $pluginareas)) {
1237 $pluginowner = $plugin;
1238 break;
1242 if (!$pluginowner) {
1243 foreach ($assignment->get_feedback_plugins() as $plugin) {
1244 if ($plugin->is_visible()) {
1245 $pluginareas = $plugin->get_file_areas();
1247 if (array_key_exists($filearea, $pluginareas)) {
1248 $pluginowner = $plugin;
1249 break;
1255 if (!$pluginowner) {
1256 return null;
1259 $result = $pluginowner->get_file_info($browser, $filearea, $itemid, $filepath, $filename);
1260 return $result;
1264 * Prints the complete info about a user's interaction with an assignment.
1266 * @param stdClass $course
1267 * @param stdClass $user
1268 * @param stdClass $coursemodule
1269 * @param stdClass $assign the database assign record
1271 * This prints the submission summary and feedback summary for this student.
1273 function assign_user_complete($course, $user, $coursemodule, $assign) {
1274 global $CFG;
1275 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1277 $context = context_module::instance($coursemodule->id);
1279 $assignment = new assign($context, $coursemodule, $course);
1281 echo $assignment->view_student_summary($user, false);
1285 * Rescale all grades for this activity and push the new grades to the gradebook.
1287 * @param stdClass $course Course db record
1288 * @param stdClass $cm Course module db record
1289 * @param float $oldmin
1290 * @param float $oldmax
1291 * @param float $newmin
1292 * @param float $newmax
1294 function assign_rescale_activity_grades($course, $cm, $oldmin, $oldmax, $newmin, $newmax) {
1295 global $DB;
1297 if ($oldmax <= $oldmin) {
1298 // Grades cannot be scaled.
1299 return false;
1301 $scale = ($newmax - $newmin) / ($oldmax - $oldmin);
1302 if (($newmax - $newmin) <= 1) {
1303 // We would lose too much precision, lets bail.
1304 return false;
1307 $params = array(
1308 'p1' => $oldmin,
1309 'p2' => $scale,
1310 'p3' => $newmin,
1311 'a' => $cm->instance
1314 // Only rescale grades that are greater than or equal to 0. Anything else is a special value.
1315 $sql = 'UPDATE {assign_grades} set grade = (((grade - :p1) * :p2) + :p3) where assignment = :a and grade >= 0';
1316 $dbupdate = $DB->execute($sql, $params);
1317 if (!$dbupdate) {
1318 return false;
1321 // Now re-push all grades to the gradebook.
1322 $dbparams = array('id' => $cm->instance);
1323 $assign = $DB->get_record('assign', $dbparams);
1324 $assign->cmidnumber = $cm->idnumber;
1326 assign_update_grades($assign);
1328 return true;
1332 * Print the grade information for the assignment for this user.
1334 * @param stdClass $course
1335 * @param stdClass $user
1336 * @param stdClass $coursemodule
1337 * @param stdClass $assignment
1339 function assign_user_outline($course, $user, $coursemodule, $assignment) {
1340 global $CFG;
1341 require_once($CFG->libdir.'/gradelib.php');
1342 require_once($CFG->dirroot.'/grade/grading/lib.php');
1344 $gradinginfo = grade_get_grades($course->id,
1345 'mod',
1346 'assign',
1347 $assignment->id,
1348 $user->id);
1350 $gradingitem = $gradinginfo->items[0];
1351 $gradebookgrade = $gradingitem->grades[$user->id];
1353 if (empty($gradebookgrade->str_long_grade)) {
1354 return null;
1356 $result = new stdClass();
1357 if (!$gradingitem->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
1358 $result->info = get_string('outlinegrade', 'assign', $gradebookgrade->str_long_grade);
1359 } else {
1360 $result->info = get_string('gradenoun') . ': ' . get_string('hidden', 'grades');
1362 $result->time = $gradebookgrade->dategraded;
1364 return $result;
1368 * Serves intro attachment files.
1370 * @param mixed $course course or id of the course
1371 * @param mixed $cm course module or id of the course module
1372 * @param context $context
1373 * @param string $filearea
1374 * @param array $args
1375 * @param bool $forcedownload
1376 * @param array $options additional options affecting the file serving
1377 * @return bool false if file not found, does not return if found - just send the file
1379 function assign_pluginfile($course,
1380 $cm,
1381 context $context,
1382 $filearea,
1383 $args,
1384 $forcedownload,
1385 array $options=array()) {
1386 global $CFG;
1388 if ($context->contextlevel != CONTEXT_MODULE) {
1389 return false;
1392 require_login($course, false, $cm);
1393 if (!has_capability('mod/assign:view', $context)) {
1394 return false;
1397 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1398 $assign = new assign($context, $cm, $course);
1400 if ($filearea !== ASSIGN_INTROATTACHMENT_FILEAREA && $filearea !== ASSIGN_ACTIVITYATTACHMENT_FILEAREA) {
1401 return false;
1403 if (!$assign->show_intro()) {
1404 return false;
1407 $itemid = (int)array_shift($args);
1408 if ($itemid != 0) {
1409 return false;
1412 $relativepath = implode('/', $args);
1414 $fullpath = "/{$context->id}/mod_assign/$filearea/$itemid/$relativepath";
1416 $fs = get_file_storage();
1417 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1418 return false;
1420 send_stored_file($file, 0, 0, $forcedownload, $options);
1424 * Serve the grading panel as a fragment.
1426 * @param array $args List of named arguments for the fragment loader.
1427 * @return string
1429 function mod_assign_output_fragment_gradingpanel($args) {
1430 global $CFG;
1432 $context = $args['context'];
1434 if ($context->contextlevel != CONTEXT_MODULE) {
1435 return null;
1437 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1438 $assign = new assign($context, null, null);
1440 $userid = clean_param($args['userid'], PARAM_INT);
1441 $attemptnumber = clean_param($args['attemptnumber'], PARAM_INT);
1442 $formdata = array();
1443 if (!empty($args['jsonformdata'])) {
1444 $serialiseddata = json_decode($args['jsonformdata']);
1445 parse_str($serialiseddata, $formdata);
1447 $viewargs = array(
1448 'userid' => $userid,
1449 'attemptnumber' => $attemptnumber,
1450 'formdata' => $formdata
1453 return $assign->view('gradingpanel', $viewargs);
1457 * Check if the module has any update that affects the current user since a given time.
1459 * @param cm_info $cm course module data
1460 * @param int $from the time to check updates from
1461 * @param array $filter if we need to check only specific updates
1462 * @return stdClass an object with the different type of areas indicating if they were updated or not
1463 * @since Moodle 3.2
1465 function assign_check_updates_since(cm_info $cm, $from, $filter = array()) {
1466 global $DB, $USER, $CFG;
1467 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1469 $updates = new stdClass();
1470 $updates = course_check_module_updates_since($cm, $from, array(ASSIGN_INTROATTACHMENT_FILEAREA), $filter);
1472 // Check if there is a new submission by the user or new grades.
1473 $select = 'assignment = :id AND userid = :userid AND (timecreated > :since1 OR timemodified > :since2)';
1474 $params = array('id' => $cm->instance, 'userid' => $USER->id, 'since1' => $from, 'since2' => $from);
1475 $updates->submissions = (object) array('updated' => false);
1476 $submissions = $DB->get_records_select('assign_submission', $select, $params, '', 'id');
1477 if (!empty($submissions)) {
1478 $updates->submissions->updated = true;
1479 $updates->submissions->itemids = array_keys($submissions);
1482 $updates->grades = (object) array('updated' => false);
1483 $grades = $DB->get_records_select('assign_grades', $select, $params, '', 'id');
1484 if (!empty($grades)) {
1485 $updates->grades->updated = true;
1486 $updates->grades->itemids = array_keys($grades);
1489 // Now, teachers should see other students updates.
1490 if (has_capability('mod/assign:viewgrades', $cm->context)) {
1491 $params = array('id' => $cm->instance, 'since1' => $from, 'since2' => $from);
1492 $select = 'assignment = :id AND (timecreated > :since1 OR timemodified > :since2)';
1494 if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS) {
1495 $groupusers = array_keys(groups_get_activity_shared_group_members($cm));
1496 if (empty($groupusers)) {
1497 return $updates;
1499 list($insql, $inparams) = $DB->get_in_or_equal($groupusers, SQL_PARAMS_NAMED);
1500 $select .= ' AND userid ' . $insql;
1501 $params = array_merge($params, $inparams);
1504 $updates->usersubmissions = (object) array('updated' => false);
1505 $submissions = $DB->get_records_select('assign_submission', $select, $params, '', 'id');
1506 if (!empty($submissions)) {
1507 $updates->usersubmissions->updated = true;
1508 $updates->usersubmissions->itemids = array_keys($submissions);
1511 $updates->usergrades = (object) array('updated' => false);
1512 $grades = $DB->get_records_select('assign_grades', $select, $params, '', 'id');
1513 if (!empty($grades)) {
1514 $updates->usergrades->updated = true;
1515 $updates->usergrades->itemids = array_keys($grades);
1519 return $updates;
1523 * Is the event visible?
1525 * This is used to determine global visibility of an event in all places throughout Moodle. For example,
1526 * the ASSIGN_EVENT_TYPE_GRADINGDUE event will not be shown to students on their calendar.
1528 * @param calendar_event $event
1529 * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
1530 * @return bool Returns true if the event is visible to the current user, false otherwise.
1532 function mod_assign_core_calendar_is_event_visible(calendar_event $event, $userid = 0) {
1533 global $CFG, $USER;
1535 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1537 if (empty($userid)) {
1538 $userid = $USER->id;
1541 $cm = get_fast_modinfo($event->courseid, $userid)->instances['assign'][$event->instance];
1542 $context = context_module::instance($cm->id);
1544 $assign = new assign($context, $cm, null);
1546 if ($event->eventtype == ASSIGN_EVENT_TYPE_GRADINGDUE) {
1547 return $assign->can_grade($userid);
1548 } else {
1549 return true;
1554 * This function receives a calendar event and returns the action associated with it, or null if there is none.
1556 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
1557 * is not displayed on the block.
1559 * @param calendar_event $event
1560 * @param \core_calendar\action_factory $factory
1561 * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
1562 * @return \core_calendar\local\event\entities\action_interface|null
1564 function mod_assign_core_calendar_provide_event_action(calendar_event $event,
1565 \core_calendar\action_factory $factory,
1566 $userid = 0) {
1568 global $CFG, $USER;
1570 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1572 if (empty($userid)) {
1573 $userid = $USER->id;
1576 $cm = get_fast_modinfo($event->courseid, $userid)->instances['assign'][$event->instance];
1577 $context = context_module::instance($cm->id);
1579 $completion = new \completion_info($cm->get_course());
1581 $completiondata = $completion->get_data($cm, false, $userid);
1583 if ($completiondata->completionstate != COMPLETION_INCOMPLETE) {
1584 return null;
1587 $assign = new assign($context, $cm, null);
1589 // Apply overrides.
1590 $assign->update_effective_access($userid);
1592 if ($event->eventtype == ASSIGN_EVENT_TYPE_GRADINGDUE) {
1593 $name = get_string('gradeverb');
1594 $url = new \moodle_url('/mod/assign/view.php', [
1595 'id' => $cm->id,
1596 'action' => 'grader'
1598 $actionable = $assign->can_grade($userid) && (time() >= $assign->get_instance()->allowsubmissionsfromdate);
1599 $itemcount = $actionable ? $assign->count_submissions_need_grading() : 0;
1600 } else {
1601 $usersubmission = $assign->get_user_submission($userid, false);
1602 if ($usersubmission && $usersubmission->status === ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
1603 // The user has already submitted.
1604 // We do not want to change the text to edit the submission, we want to remove the event from the Dashboard entirely.
1605 return null;
1608 $participant = $assign->get_participant($userid);
1610 if (!$participant) {
1611 // If the user is not a participant in the assignment then they have
1612 // no action to take. This will filter out the events for teachers.
1613 return null;
1616 // The user has not yet submitted anything. Show the addsubmission link.
1617 $name = get_string('addsubmission', 'assign');
1618 $url = new \moodle_url('/mod/assign/view.php', [
1619 'id' => $cm->id,
1620 'action' => 'editsubmission'
1622 $itemcount = 1;
1623 $actionable = $assign->is_any_submission_plugin_enabled() && $assign->can_edit_submission($userid, $userid);
1626 return $factory->create_instance(
1627 $name,
1628 $url,
1629 $itemcount,
1630 $actionable
1635 * Callback function that determines whether an action event should be showing its item count
1636 * based on the event type and the item count.
1638 * @param calendar_event $event The calendar event.
1639 * @param int $itemcount The item count associated with the action event.
1640 * @return bool
1642 function mod_assign_core_calendar_event_action_shows_item_count(calendar_event $event, $itemcount = 0) {
1643 // List of event types where the action event's item count should be shown.
1644 $eventtypesshowingitemcount = [
1645 ASSIGN_EVENT_TYPE_GRADINGDUE
1647 // For mod_assign, item count should be shown if the event type is 'gradingdue' and there is one or more item count.
1648 return in_array($event->eventtype, $eventtypesshowingitemcount) && $itemcount > 0;
1652 * This function calculates the minimum and maximum cutoff values for the timestart of
1653 * the given event.
1655 * It will return an array with two values, the first being the minimum cutoff value and
1656 * the second being the maximum cutoff value. Either or both values can be null, which
1657 * indicates there is no minimum or maximum, respectively.
1659 * If a cutoff is required then the function must return an array containing the cutoff
1660 * timestamp and error string to display to the user if the cutoff value is violated.
1662 * A minimum and maximum cutoff return value will look like:
1664 * [1505704373, 'The due date must be after the sbumission start date'],
1665 * [1506741172, 'The due date must be before the cutoff date']
1668 * If the event does not have a valid timestart range then [false, false] will
1669 * be returned.
1671 * @param calendar_event $event The calendar event to get the time range for
1672 * @param stdClass $instance The module instance to get the range from
1673 * @return array
1675 function mod_assign_core_calendar_get_valid_event_timestart_range(\calendar_event $event, \stdClass $instance) {
1676 global $CFG;
1678 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1680 $courseid = $event->courseid;
1681 $modulename = $event->modulename;
1682 $instanceid = $event->instance;
1683 $coursemodule = get_fast_modinfo($courseid)->instances[$modulename][$instanceid];
1684 $context = context_module::instance($coursemodule->id);
1685 $assign = new assign($context, null, null);
1686 $assign->set_instance($instance);
1688 return $assign->get_valid_calendar_event_timestart_range($event);
1692 * This function will update the assign module according to the
1693 * event that has been modified.
1695 * @throws \moodle_exception
1696 * @param \calendar_event $event
1697 * @param stdClass $instance The module instance to get the range from
1699 function mod_assign_core_calendar_event_timestart_updated(\calendar_event $event, \stdClass $instance) {
1700 global $CFG, $DB;
1702 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1704 if (empty($event->instance) || $event->modulename != 'assign') {
1705 return;
1708 if ($instance->id != $event->instance) {
1709 return;
1712 if (!in_array($event->eventtype, [ASSIGN_EVENT_TYPE_DUE, ASSIGN_EVENT_TYPE_GRADINGDUE])) {
1713 return;
1716 $courseid = $event->courseid;
1717 $modulename = $event->modulename;
1718 $instanceid = $event->instance;
1719 $modified = false;
1720 $coursemodule = get_fast_modinfo($courseid)->instances[$modulename][$instanceid];
1721 $context = context_module::instance($coursemodule->id);
1723 // The user does not have the capability to modify this activity.
1724 if (!has_capability('moodle/course:manageactivities', $context)) {
1725 return;
1728 $assign = new assign($context, $coursemodule, null);
1729 $assign->set_instance($instance);
1731 if ($event->eventtype == ASSIGN_EVENT_TYPE_DUE) {
1732 // This check is in here because due date events are currently
1733 // the only events that can be overridden, so we can save a DB
1734 // query if we don't bother checking other events.
1735 if ($assign->is_override_calendar_event($event)) {
1736 // This is an override event so we should ignore it.
1737 return;
1740 $newduedate = $event->timestart;
1742 if ($newduedate != $instance->duedate) {
1743 $instance->duedate = $newduedate;
1744 $modified = true;
1746 } else if ($event->eventtype == ASSIGN_EVENT_TYPE_GRADINGDUE) {
1747 $newduedate = $event->timestart;
1749 if ($newduedate != $instance->gradingduedate) {
1750 $instance->gradingduedate = $newduedate;
1751 $modified = true;
1755 if ($modified) {
1756 $instance->timemodified = time();
1757 // Persist the assign instance changes.
1758 $DB->update_record('assign', $instance);
1759 $assign->update_calendar($coursemodule->id);
1760 $event = \core\event\course_module_updated::create_from_cm($coursemodule, $context);
1761 $event->trigger();
1766 * Return a list of all the user preferences used by mod_assign.
1768 * @return array
1770 function mod_assign_user_preferences() {
1771 $preferences = array();
1772 $preferences['assign_filter'] = array(
1773 'type' => PARAM_ALPHA,
1774 'null' => NULL_NOT_ALLOWED,
1775 'default' => ''
1777 $preferences['assign_workflowfilter'] = array(
1778 'type' => PARAM_ALPHA,
1779 'null' => NULL_NOT_ALLOWED,
1780 'default' => ''
1782 $preferences['assign_markerfilter'] = array(
1783 'type' => PARAM_ALPHANUMEXT,
1784 'null' => NULL_NOT_ALLOWED,
1785 'default' => ''
1788 return $preferences;
1792 * Given an array with a file path, it returns the itemid and the filepath for the defined filearea.
1794 * @param string $filearea The filearea.
1795 * @param array $args The path (the part after the filearea and before the filename).
1796 * @return array The itemid and the filepath inside the $args path, for the defined filearea.
1798 function mod_assign_get_path_from_pluginfile(string $filearea, array $args) : array {
1799 // Assign never has an itemid (the number represents the revision but it's not stored in database).
1800 array_shift($args);
1802 // Get the filepath.
1803 if (empty($args)) {
1804 $filepath = '/';
1805 } else {
1806 $filepath = '/' . implode('/', $args) . '/';
1809 return [
1810 'itemid' => 0,
1811 'filepath' => $filepath,
1816 * Callback to fetch the activity event type lang string.
1818 * @param string $eventtype The event type.
1819 * @return lang_string The event type lang string.
1821 function mod_assign_core_calendar_get_event_action_string(string $eventtype): string {
1822 $modulename = get_string('modulename', 'assign');
1824 switch ($eventtype) {
1825 case ASSIGN_EVENT_TYPE_DUE:
1826 $identifier = 'calendardue';
1827 break;
1828 case ASSIGN_EVENT_TYPE_GRADINGDUE:
1829 $identifier = 'calendargradingdue';
1830 break;
1831 default:
1832 return get_string('requiresaction', 'calendar', $modulename);
1835 return get_string($identifier, 'assign', $modulename);