MDL-36754 core_files: Support tokens when rewriting text
[moodle.git] / mod / assign / lib.php
blobee787849bc422925abd7f44c6196bcf3ed955357
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);
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 continue;
540 $descriptions[] = get_string('completionsubmit', 'assign');
541 break;
542 default:
543 break;
546 return $descriptions;
550 * Return a list of page types
551 * @param string $pagetype current page type
552 * @param stdClass $parentcontext Block's parent context
553 * @param stdClass $currentcontext Current context of block
555 function assign_page_type_list($pagetype, $parentcontext, $currentcontext) {
556 $modulepagetype = array(
557 'mod-assign-*' => get_string('page-mod-assign-x', 'assign'),
558 'mod-assign-view' => get_string('page-mod-assign-view', 'assign'),
560 return $modulepagetype;
564 * Print an overview of all assignments
565 * for the courses.
567 * @deprecated since 3.3
568 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
569 * @param mixed $courses The list of courses to print the overview for
570 * @param array $htmlarray The array of html to return
571 * @return true
573 function assign_print_overview($courses, &$htmlarray) {
574 global $CFG, $DB;
576 debugging('The function assign_print_overview() is now deprecated.', DEBUG_DEVELOPER);
578 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
579 return true;
582 if (!$assignments = get_all_instances_in_courses('assign', $courses)) {
583 return true;
586 $assignmentids = array();
588 // Do assignment_base::isopen() here without loading the whole thing for speed.
589 foreach ($assignments as $key => $assignment) {
590 $time = time();
591 $isopen = false;
592 if ($assignment->duedate) {
593 $duedate = false;
594 if ($assignment->cutoffdate) {
595 $duedate = $assignment->cutoffdate;
597 if ($duedate) {
598 $isopen = ($assignment->allowsubmissionsfromdate <= $time && $time <= $duedate);
599 } else {
600 $isopen = ($assignment->allowsubmissionsfromdate <= $time);
603 if ($isopen) {
604 $assignmentids[] = $assignment->id;
608 if (empty($assignmentids)) {
609 // No assignments to look at - we're done.
610 return true;
613 // Definitely something to print, now include the constants we need.
614 require_once($CFG->dirroot . '/mod/assign/locallib.php');
616 $strduedate = get_string('duedate', 'assign');
617 $strcutoffdate = get_string('nosubmissionsacceptedafter', 'assign');
618 $strnolatesubmissions = get_string('nolatesubmissions', 'assign');
619 $strduedateno = get_string('duedateno', 'assign');
620 $strassignment = get_string('modulename', 'assign');
622 // We do all possible database work here *outside* of the loop to ensure this scales.
623 list($sqlassignmentids, $assignmentidparams) = $DB->get_in_or_equal($assignmentids);
625 $mysubmissions = null;
626 $unmarkedsubmissions = null;
628 foreach ($assignments as $assignment) {
630 // Do not show assignments that are not open.
631 if (!in_array($assignment->id, $assignmentids)) {
632 continue;
635 $context = context_module::instance($assignment->coursemodule);
637 // Does the submission status of the assignment require notification?
638 if (has_capability('mod/assign:submit', $context, null, false)) {
639 // Does the submission status of the assignment require notification?
640 $submitdetails = assign_get_mysubmission_details_for_print_overview($mysubmissions, $sqlassignmentids,
641 $assignmentidparams, $assignment);
642 } else {
643 $submitdetails = false;
646 if (has_capability('mod/assign:grade', $context, null, false)) {
647 // Does the grading status of the assignment require notification ?
648 $gradedetails = assign_get_grade_details_for_print_overview($unmarkedsubmissions, $sqlassignmentids,
649 $assignmentidparams, $assignment, $context);
650 } else {
651 $gradedetails = false;
654 if (empty($submitdetails) && empty($gradedetails)) {
655 // There is no need to display this assignment as there is nothing to notify.
656 continue;
659 $dimmedclass = '';
660 if (!$assignment->visible) {
661 $dimmedclass = ' class="dimmed"';
663 $href = $CFG->wwwroot . '/mod/assign/view.php?id=' . $assignment->coursemodule;
664 $basestr = '<div class="assign overview">' .
665 '<div class="name">' .
666 $strassignment . ': '.
667 '<a ' . $dimmedclass .
668 'title="' . $strassignment . '" ' .
669 'href="' . $href . '">' .
670 format_string($assignment->name) .
671 '</a></div>';
672 if ($assignment->duedate) {
673 $userdate = userdate($assignment->duedate);
674 $basestr .= '<div class="info">' . $strduedate . ': ' . $userdate . '</div>';
675 } else {
676 $basestr .= '<div class="info">' . $strduedateno . '</div>';
678 if ($assignment->cutoffdate) {
679 if ($assignment->cutoffdate == $assignment->duedate) {
680 $basestr .= '<div class="info">' . $strnolatesubmissions . '</div>';
681 } else {
682 $userdate = userdate($assignment->cutoffdate);
683 $basestr .= '<div class="info">' . $strcutoffdate . ': ' . $userdate . '</div>';
687 // Show only relevant information.
688 if (!empty($submitdetails)) {
689 $basestr .= $submitdetails;
692 if (!empty($gradedetails)) {
693 $basestr .= $gradedetails;
695 $basestr .= '</div>';
697 if (empty($htmlarray[$assignment->course]['assign'])) {
698 $htmlarray[$assignment->course]['assign'] = $basestr;
699 } else {
700 $htmlarray[$assignment->course]['assign'] .= $basestr;
703 return true;
707 * This api generates html to be displayed to students in print overview section, related to their submission status of the given
708 * assignment.
710 * @deprecated since 3.3
711 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
712 * @param array $mysubmissions list of submissions of current user indexed by assignment id.
713 * @param string $sqlassignmentids sql clause used to filter open assignments.
714 * @param array $assignmentidparams sql params used to filter open assignments.
715 * @param stdClass $assignment current assignment
717 * @return bool|string html to display , false if nothing needs to be displayed.
718 * @throws coding_exception
720 function assign_get_mysubmission_details_for_print_overview(&$mysubmissions, $sqlassignmentids, $assignmentidparams,
721 $assignment) {
722 global $USER, $DB;
724 debugging('The function assign_get_mysubmission_details_for_print_overview() is now deprecated.', DEBUG_DEVELOPER);
726 if ($assignment->nosubmissions) {
727 // Offline assignment. No need to display alerts for offline assignments.
728 return false;
731 $strnotsubmittedyet = get_string('notsubmittedyet', 'assign');
733 if (!isset($mysubmissions)) {
735 // Get all user submissions, indexed by assignment id.
736 $dbparams = array_merge(array($USER->id), $assignmentidparams, array($USER->id));
737 $mysubmissions = $DB->get_records_sql('SELECT a.id AS assignment,
738 a.nosubmissions AS nosubmissions,
739 g.timemodified AS timemarked,
740 g.grader AS grader,
741 g.grade AS grade,
742 s.status AS status
743 FROM {assign} a, {assign_submission} s
744 LEFT JOIN {assign_grades} g ON
745 g.assignment = s.assignment AND
746 g.userid = ? AND
747 g.attemptnumber = s.attemptnumber
748 WHERE a.id ' . $sqlassignmentids . ' AND
749 s.latest = 1 AND
750 s.assignment = a.id AND
751 s.userid = ?', $dbparams);
754 $submitdetails = '';
755 $submitdetails .= '<div class="details">';
756 $submitdetails .= get_string('mysubmission', 'assign');
757 $submission = false;
759 if (isset($mysubmissions[$assignment->id])) {
760 $submission = $mysubmissions[$assignment->id];
763 if ($submission && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
764 // A valid submission already exists, no need to notify students about this.
765 return false;
768 // We need to show details only if a valid submission doesn't exist.
769 if (!$submission ||
770 !$submission->status ||
771 $submission->status == ASSIGN_SUBMISSION_STATUS_DRAFT ||
772 $submission->status == ASSIGN_SUBMISSION_STATUS_NEW
774 $submitdetails .= $strnotsubmittedyet;
775 } else {
776 $submitdetails .= get_string('submissionstatus_' . $submission->status, 'assign');
778 if ($assignment->markingworkflow) {
779 $workflowstate = $DB->get_field('assign_user_flags', 'workflowstate', array('assignment' =>
780 $assignment->id, 'userid' => $USER->id));
781 if ($workflowstate) {
782 $gradingstatus = 'markingworkflowstate' . $workflowstate;
783 } else {
784 $gradingstatus = 'markingworkflowstate' . ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED;
786 } else if (!empty($submission->grade) && $submission->grade !== null && $submission->grade >= 0) {
787 $gradingstatus = ASSIGN_GRADING_STATUS_GRADED;
788 } else {
789 $gradingstatus = ASSIGN_GRADING_STATUS_NOT_GRADED;
791 $submitdetails .= ', ' . get_string($gradingstatus, 'assign');
792 $submitdetails .= '</div>';
793 return $submitdetails;
797 * This api generates html to be displayed to teachers in print overview section, related to the grading status of the given
798 * assignment's submissions.
800 * @deprecated since 3.3
801 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
802 * @param array $unmarkedsubmissions list of submissions of that are currently unmarked indexed by assignment id.
803 * @param string $sqlassignmentids sql clause used to filter open assignments.
804 * @param array $assignmentidparams sql params used to filter open assignments.
805 * @param stdClass $assignment current assignment
806 * @param context $context context of the assignment.
808 * @return bool|string html to display , false if nothing needs to be displayed.
809 * @throws coding_exception
811 function assign_get_grade_details_for_print_overview(&$unmarkedsubmissions, $sqlassignmentids, $assignmentidparams,
812 $assignment, $context) {
813 global $DB;
815 debugging('The function assign_get_grade_details_for_print_overview() is now deprecated.', DEBUG_DEVELOPER);
817 if (!isset($unmarkedsubmissions)) {
818 // Build up and array of unmarked submissions indexed by assignment id/ userid
819 // for use where the user has grading rights on assignment.
820 $dbparams = array_merge(array(ASSIGN_SUBMISSION_STATUS_SUBMITTED), $assignmentidparams);
821 $rs = $DB->get_recordset_sql('SELECT s.assignment as assignment,
822 s.userid as userid,
823 s.id as id,
824 s.status as status,
825 g.timemodified as timegraded
826 FROM {assign_submission} s
827 LEFT JOIN {assign_grades} g ON
828 s.userid = g.userid AND
829 s.assignment = g.assignment AND
830 g.attemptnumber = s.attemptnumber
831 LEFT JOIN {assign} a ON
832 a.id = s.assignment
833 WHERE
834 ( g.timemodified is NULL OR
835 s.timemodified >= g.timemodified OR
836 g.grade IS NULL OR
837 (g.grade = -1 AND
838 a.grade < 0)) AND
839 s.timemodified IS NOT NULL AND
840 s.status = ? AND
841 s.latest = 1 AND
842 s.assignment ' . $sqlassignmentids, $dbparams);
844 $unmarkedsubmissions = array();
845 foreach ($rs as $rd) {
846 $unmarkedsubmissions[$rd->assignment][$rd->userid] = $rd->id;
848 $rs->close();
851 // Count how many people can submit.
852 $submissions = 0;
853 if ($students = get_enrolled_users($context, 'mod/assign:view', 0, 'u.id')) {
854 foreach ($students as $student) {
855 if (isset($unmarkedsubmissions[$assignment->id][$student->id])) {
856 $submissions++;
861 if ($submissions) {
862 $urlparams = array('id' => $assignment->coursemodule, 'action' => 'grading');
863 $url = new moodle_url('/mod/assign/view.php', $urlparams);
864 $gradedetails = '<div class="details">' .
865 '<a href="' . $url . '">' .
866 get_string('submissionsnotgraded', 'assign', $submissions) .
867 '</a></div>';
868 return $gradedetails;
869 } else {
870 return false;
876 * Print recent activity from all assignments in a given course
878 * This is used by the recent activity block
879 * @param mixed $course the course to print activity for
880 * @param bool $viewfullnames boolean to determine whether to show full names or not
881 * @param int $timestart the time the rendering started
882 * @return bool true if activity was printed, false otherwise.
884 function assign_print_recent_activity($course, $viewfullnames, $timestart) {
885 global $CFG, $USER, $DB, $OUTPUT;
886 require_once($CFG->dirroot . '/mod/assign/locallib.php');
888 // Do not use log table if possible, it may be huge.
890 $dbparams = array($timestart, $course->id, 'assign', ASSIGN_SUBMISSION_STATUS_SUBMITTED);
891 $namefields = user_picture::fields('u', null, 'userid');
892 if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, um.id as recordid,
893 $namefields
894 FROM {assign_submission} asb
895 JOIN {assign} a ON a.id = asb.assignment
896 JOIN {course_modules} cm ON cm.instance = a.id
897 JOIN {modules} md ON md.id = cm.module
898 JOIN {user} u ON u.id = asb.userid
899 LEFT JOIN {assign_user_mapping} um ON um.userid = u.id AND um.assignment = a.id
900 WHERE asb.timemodified > ? AND
901 asb.latest = 1 AND
902 a.course = ? AND
903 md.name = ? AND
904 asb.status = ?
905 ORDER BY asb.timemodified ASC", $dbparams)) {
906 return false;
909 $modinfo = get_fast_modinfo($course);
910 $show = array();
911 $grader = array();
913 $showrecentsubmissions = get_config('assign', 'showrecentsubmissions');
915 foreach ($submissions as $submission) {
916 if (!array_key_exists($submission->cmid, $modinfo->get_cms())) {
917 continue;
919 $cm = $modinfo->get_cm($submission->cmid);
920 if (!$cm->uservisible) {
921 continue;
923 if ($submission->userid == $USER->id) {
924 $show[] = $submission;
925 continue;
928 $context = context_module::instance($submission->cmid);
929 // The act of submitting of assignment may be considered private -
930 // only graders will see it if specified.
931 if (empty($showrecentsubmissions)) {
932 if (!array_key_exists($cm->id, $grader)) {
933 $grader[$cm->id] = has_capability('moodle/grade:viewall', $context);
935 if (!$grader[$cm->id]) {
936 continue;
940 $groupmode = groups_get_activity_groupmode($cm, $course);
942 if ($groupmode == SEPARATEGROUPS &&
943 !has_capability('moodle/site:accessallgroups', $context)) {
944 if (isguestuser()) {
945 // Shortcut - guest user does not belong into any group.
946 continue;
949 // This will be slow - show only users that share group with me in this cm.
950 if (!$modinfo->get_groups($cm->groupingid)) {
951 continue;
953 $usersgroups = groups_get_all_groups($course->id, $submission->userid, $cm->groupingid);
954 if (is_array($usersgroups)) {
955 $usersgroups = array_keys($usersgroups);
956 $intersect = array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid));
957 if (empty($intersect)) {
958 continue;
962 $show[] = $submission;
965 if (empty($show)) {
966 return false;
969 echo $OUTPUT->heading(get_string('newsubmissions', 'assign').':', 3);
971 foreach ($show as $submission) {
972 $cm = $modinfo->get_cm($submission->cmid);
973 $context = context_module::instance($submission->cmid);
974 $assign = new assign($context, $cm, $cm->course);
975 $link = $CFG->wwwroot.'/mod/assign/view.php?id='.$cm->id;
976 // Obscure first and last name if blind marking enabled.
977 if ($assign->is_blind_marking()) {
978 $submission->firstname = get_string('participant', 'mod_assign');
979 if (empty($submission->recordid)) {
980 $submission->recordid = $assign->get_uniqueid_for_user($submission->userid);
982 $submission->lastname = $submission->recordid;
984 print_recent_activity_note($submission->timemodified,
985 $submission,
986 $cm->name,
987 $link,
988 false,
989 $viewfullnames);
992 return true;
996 * Returns all assignments since a given time.
998 * @param array $activities The activity information is returned in this array
999 * @param int $index The current index in the activities array
1000 * @param int $timestart The earliest activity to show
1001 * @param int $courseid Limit the search to this course
1002 * @param int $cmid The course module id
1003 * @param int $userid Optional user id
1004 * @param int $groupid Optional group id
1005 * @return void
1007 function assign_get_recent_mod_activity(&$activities,
1008 &$index,
1009 $timestart,
1010 $courseid,
1011 $cmid,
1012 $userid=0,
1013 $groupid=0) {
1014 global $CFG, $COURSE, $USER, $DB;
1016 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1018 if ($COURSE->id == $courseid) {
1019 $course = $COURSE;
1020 } else {
1021 $course = $DB->get_record('course', array('id'=>$courseid));
1024 $modinfo = get_fast_modinfo($course);
1026 $cm = $modinfo->get_cm($cmid);
1027 $params = array();
1028 if ($userid) {
1029 $userselect = 'AND u.id = :userid';
1030 $params['userid'] = $userid;
1031 } else {
1032 $userselect = '';
1035 if ($groupid) {
1036 $groupselect = 'AND gm.groupid = :groupid';
1037 $groupjoin = 'JOIN {groups_members} gm ON gm.userid=u.id';
1038 $params['groupid'] = $groupid;
1039 } else {
1040 $groupselect = '';
1041 $groupjoin = '';
1044 $params['cminstance'] = $cm->instance;
1045 $params['timestart'] = $timestart;
1046 $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1048 $userfields = user_picture::fields('u', null, 'userid');
1050 if (!$submissions = $DB->get_records_sql('SELECT asb.id, asb.timemodified, ' .
1051 $userfields .
1052 ' FROM {assign_submission} asb
1053 JOIN {assign} a ON a.id = asb.assignment
1054 JOIN {user} u ON u.id = asb.userid ' .
1055 $groupjoin .
1056 ' WHERE asb.timemodified > :timestart AND
1057 asb.status = :submitted AND
1058 a.id = :cminstance
1059 ' . $userselect . ' ' . $groupselect .
1060 ' ORDER BY asb.timemodified ASC', $params)) {
1061 return;
1064 $groupmode = groups_get_activity_groupmode($cm, $course);
1065 $cmcontext = context_module::instance($cm->id);
1066 $grader = has_capability('moodle/grade:viewall', $cmcontext);
1067 $accessallgroups = has_capability('moodle/site:accessallgroups', $cmcontext);
1068 $viewfullnames = has_capability('moodle/site:viewfullnames', $cmcontext);
1071 $showrecentsubmissions = get_config('assign', 'showrecentsubmissions');
1072 $show = array();
1073 foreach ($submissions as $submission) {
1074 if ($submission->userid == $USER->id) {
1075 $show[] = $submission;
1076 continue;
1078 // The act of submitting of assignment may be considered private -
1079 // only graders will see it if specified.
1080 if (empty($showrecentsubmissions)) {
1081 if (!$grader) {
1082 continue;
1086 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
1087 if (isguestuser()) {
1088 // Shortcut - guest user does not belong into any group.
1089 continue;
1092 // This will be slow - show only users that share group with me in this cm.
1093 if (!$modinfo->get_groups($cm->groupingid)) {
1094 continue;
1096 $usersgroups = groups_get_all_groups($course->id, $submission->userid, $cm->groupingid);
1097 if (is_array($usersgroups)) {
1098 $usersgroups = array_keys($usersgroups);
1099 $intersect = array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid));
1100 if (empty($intersect)) {
1101 continue;
1105 $show[] = $submission;
1108 if (empty($show)) {
1109 return;
1112 if ($grader) {
1113 require_once($CFG->libdir.'/gradelib.php');
1114 $userids = array();
1115 foreach ($show as $id => $submission) {
1116 $userids[] = $submission->userid;
1118 $grades = grade_get_grades($courseid, 'mod', 'assign', $cm->instance, $userids);
1121 $aname = format_string($cm->name, true);
1122 foreach ($show as $submission) {
1123 $activity = new stdClass();
1125 $activity->type = 'assign';
1126 $activity->cmid = $cm->id;
1127 $activity->name = $aname;
1128 $activity->sectionnum = $cm->sectionnum;
1129 $activity->timestamp = $submission->timemodified;
1130 $activity->user = new stdClass();
1131 if ($grader) {
1132 $activity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
1135 $userfields = explode(',', user_picture::fields());
1136 foreach ($userfields as $userfield) {
1137 if ($userfield == 'id') {
1138 // Aliased in SQL above.
1139 $activity->user->{$userfield} = $submission->userid;
1140 } else {
1141 $activity->user->{$userfield} = $submission->{$userfield};
1144 $activity->user->fullname = fullname($submission, $viewfullnames);
1146 $activities[$index++] = $activity;
1149 return;
1153 * Print recent activity from all assignments in a given course
1155 * This is used by course/recent.php
1156 * @param stdClass $activity
1157 * @param int $courseid
1158 * @param bool $detail
1159 * @param array $modnames
1161 function assign_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
1162 global $CFG, $OUTPUT;
1164 echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
1166 echo '<tr><td class="userpicture" valign="top">';
1167 echo $OUTPUT->user_picture($activity->user);
1168 echo '</td><td>';
1170 if ($detail) {
1171 $modname = $modnames[$activity->type];
1172 echo '<div class="title">';
1173 echo $OUTPUT->image_icon('icon', $modname, 'assign');
1174 echo '<a href="' . $CFG->wwwroot . '/mod/assign/view.php?id=' . $activity->cmid . '">';
1175 echo $activity->name;
1176 echo '</a>';
1177 echo '</div>';
1180 if (isset($activity->grade)) {
1181 echo '<div class="grade">';
1182 echo get_string('grade').': ';
1183 echo $activity->grade;
1184 echo '</div>';
1187 echo '<div class="user">';
1188 echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->id}&amp;course=$courseid\">";
1189 echo "{$activity->user->fullname}</a> - " . userdate($activity->timestamp);
1190 echo '</div>';
1192 echo '</td></tr></table>';
1196 * Checks if a scale is being used by an assignment.
1198 * This is used by the backup code to decide whether to back up a scale
1199 * @param int $assignmentid
1200 * @param int $scaleid
1201 * @return boolean True if the scale is used by the assignment
1203 function assign_scale_used($assignmentid, $scaleid) {
1204 global $DB;
1206 $return = false;
1207 $rec = $DB->get_record('assign', array('id'=>$assignmentid, 'grade'=>-$scaleid));
1209 if (!empty($rec) && !empty($scaleid)) {
1210 $return = true;
1213 return $return;
1217 * Checks if scale is being used by any instance of assignment
1219 * This is used to find out if scale used anywhere
1220 * @param int $scaleid
1221 * @return boolean True if the scale is used by any assignment
1223 function assign_scale_used_anywhere($scaleid) {
1224 global $DB;
1226 if ($scaleid and $DB->record_exists('assign', array('grade'=>-$scaleid))) {
1227 return true;
1228 } else {
1229 return false;
1234 * List the actions that correspond to a view of this module.
1235 * This is used by the participation report.
1237 * Note: This is not used by new logging system. Event with
1238 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
1239 * be considered as view action.
1241 * @return array
1243 function assign_get_view_actions() {
1244 return array('view submission', 'view feedback');
1248 * List the actions that correspond to a post of this module.
1249 * This is used by the participation report.
1251 * Note: This is not used by new logging system. Event with
1252 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
1253 * will be considered as post action.
1255 * @return array
1257 function assign_get_post_actions() {
1258 return array('upload', 'submit', 'submit for grading');
1262 * Call cron on the assign module.
1264 function assign_cron() {
1265 global $CFG;
1267 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1268 assign::cron();
1270 $plugins = core_component::get_plugin_list('assignsubmission');
1272 foreach ($plugins as $name => $plugin) {
1273 $disabled = get_config('assignsubmission_' . $name, 'disabled');
1274 if (!$disabled) {
1275 $class = 'assign_submission_' . $name;
1276 require_once($CFG->dirroot . '/mod/assign/submission/' . $name . '/locallib.php');
1277 $class::cron();
1280 $plugins = core_component::get_plugin_list('assignfeedback');
1282 foreach ($plugins as $name => $plugin) {
1283 $disabled = get_config('assignfeedback_' . $name, 'disabled');
1284 if (!$disabled) {
1285 $class = 'assign_feedback_' . $name;
1286 require_once($CFG->dirroot . '/mod/assign/feedback/' . $name . '/locallib.php');
1287 $class::cron();
1291 return true;
1295 * Returns all other capabilities used by this module.
1296 * @return array Array of capability strings
1298 function assign_get_extra_capabilities() {
1299 return array('gradereport/grader:view',
1300 'moodle/grade:viewall',
1301 'moodle/site:viewfullnames',
1302 'moodle/site:config');
1306 * Create grade item for given assignment.
1308 * @param stdClass $assign record with extra cmidnumber
1309 * @param array $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
1310 * @return int 0 if ok, error code otherwise
1312 function assign_grade_item_update($assign, $grades=null) {
1313 global $CFG;
1314 require_once($CFG->libdir.'/gradelib.php');
1316 if (!isset($assign->courseid)) {
1317 $assign->courseid = $assign->course;
1320 $params = array('itemname'=>$assign->name, 'idnumber'=>$assign->cmidnumber);
1322 // Check if feedback plugin for gradebook is enabled, if yes then
1323 // gradetype = GRADE_TYPE_TEXT else GRADE_TYPE_NONE.
1324 $gradefeedbackenabled = false;
1326 if (isset($assign->gradefeedbackenabled)) {
1327 $gradefeedbackenabled = $assign->gradefeedbackenabled;
1328 } else if ($assign->grade == 0) { // Grade feedback is needed only when grade == 0.
1329 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1330 $mod = get_coursemodule_from_instance('assign', $assign->id, $assign->courseid);
1331 $cm = context_module::instance($mod->id);
1332 $assignment = new assign($cm, null, null);
1333 $gradefeedbackenabled = $assignment->is_gradebook_feedback_enabled();
1336 if ($assign->grade > 0) {
1337 $params['gradetype'] = GRADE_TYPE_VALUE;
1338 $params['grademax'] = $assign->grade;
1339 $params['grademin'] = 0;
1341 } else if ($assign->grade < 0) {
1342 $params['gradetype'] = GRADE_TYPE_SCALE;
1343 $params['scaleid'] = -$assign->grade;
1345 } else if ($gradefeedbackenabled) {
1346 // $assign->grade == 0 and feedback enabled.
1347 $params['gradetype'] = GRADE_TYPE_TEXT;
1348 } else {
1349 // $assign->grade == 0 and no feedback enabled.
1350 $params['gradetype'] = GRADE_TYPE_NONE;
1353 if ($grades === 'reset') {
1354 $params['reset'] = true;
1355 $grades = null;
1358 return grade_update('mod/assign',
1359 $assign->courseid,
1360 'mod',
1361 'assign',
1362 $assign->id,
1364 $grades,
1365 $params);
1369 * Return grade for given user or all users.
1371 * @param stdClass $assign record of assign with an additional cmidnumber
1372 * @param int $userid optional user id, 0 means all users
1373 * @return array array of grades, false if none
1375 function assign_get_user_grades($assign, $userid=0) {
1376 global $CFG;
1378 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1380 $cm = get_coursemodule_from_instance('assign', $assign->id, 0, false, MUST_EXIST);
1381 $context = context_module::instance($cm->id);
1382 $assignment = new assign($context, null, null);
1383 $assignment->set_instance($assign);
1384 return $assignment->get_user_grades_for_gradebook($userid);
1388 * Update activity grades.
1390 * @param stdClass $assign database record
1391 * @param int $userid specific user only, 0 means all
1392 * @param bool $nullifnone - not used
1394 function assign_update_grades($assign, $userid=0, $nullifnone=true) {
1395 global $CFG;
1396 require_once($CFG->libdir.'/gradelib.php');
1398 if ($assign->grade == 0) {
1399 assign_grade_item_update($assign);
1401 } else if ($grades = assign_get_user_grades($assign, $userid)) {
1402 foreach ($grades as $k => $v) {
1403 if ($v->rawgrade == -1) {
1404 $grades[$k]->rawgrade = null;
1407 assign_grade_item_update($assign, $grades);
1409 } else {
1410 assign_grade_item_update($assign);
1415 * List the file areas that can be browsed.
1417 * @param stdClass $course
1418 * @param stdClass $cm
1419 * @param stdClass $context
1420 * @return array
1422 function assign_get_file_areas($course, $cm, $context) {
1423 global $CFG;
1424 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1426 $areas = array(ASSIGN_INTROATTACHMENT_FILEAREA => get_string('introattachments', 'mod_assign'));
1428 $assignment = new assign($context, $cm, $course);
1429 foreach ($assignment->get_submission_plugins() as $plugin) {
1430 if ($plugin->is_visible()) {
1431 $pluginareas = $plugin->get_file_areas();
1433 if ($pluginareas) {
1434 $areas = array_merge($areas, $pluginareas);
1438 foreach ($assignment->get_feedback_plugins() as $plugin) {
1439 if ($plugin->is_visible()) {
1440 $pluginareas = $plugin->get_file_areas();
1442 if ($pluginareas) {
1443 $areas = array_merge($areas, $pluginareas);
1448 return $areas;
1452 * File browsing support for assign module.
1454 * @param file_browser $browser
1455 * @param object $areas
1456 * @param object $course
1457 * @param object $cm
1458 * @param object $context
1459 * @param string $filearea
1460 * @param int $itemid
1461 * @param string $filepath
1462 * @param string $filename
1463 * @return object file_info instance or null if not found
1465 function assign_get_file_info($browser,
1466 $areas,
1467 $course,
1468 $cm,
1469 $context,
1470 $filearea,
1471 $itemid,
1472 $filepath,
1473 $filename) {
1474 global $CFG;
1475 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1477 if ($context->contextlevel != CONTEXT_MODULE) {
1478 return null;
1481 $urlbase = $CFG->wwwroot.'/pluginfile.php';
1482 $fs = get_file_storage();
1483 $filepath = is_null($filepath) ? '/' : $filepath;
1484 $filename = is_null($filename) ? '.' : $filename;
1486 // Need to find where this belongs to.
1487 $assignment = new assign($context, $cm, $course);
1488 if ($filearea === ASSIGN_INTROATTACHMENT_FILEAREA) {
1489 if (!has_capability('moodle/course:managefiles', $context)) {
1490 // Students can not peak here!
1491 return null;
1493 if (!($storedfile = $fs->get_file($assignment->get_context()->id,
1494 'mod_assign', $filearea, 0, $filepath, $filename))) {
1495 return null;
1497 return new file_info_stored($browser,
1498 $assignment->get_context(),
1499 $storedfile,
1500 $urlbase,
1501 $filearea,
1502 $itemid,
1503 true,
1504 true,
1505 false);
1508 $pluginowner = null;
1509 foreach ($assignment->get_submission_plugins() as $plugin) {
1510 if ($plugin->is_visible()) {
1511 $pluginareas = $plugin->get_file_areas();
1513 if (array_key_exists($filearea, $pluginareas)) {
1514 $pluginowner = $plugin;
1515 break;
1519 if (!$pluginowner) {
1520 foreach ($assignment->get_feedback_plugins() as $plugin) {
1521 if ($plugin->is_visible()) {
1522 $pluginareas = $plugin->get_file_areas();
1524 if (array_key_exists($filearea, $pluginareas)) {
1525 $pluginowner = $plugin;
1526 break;
1532 if (!$pluginowner) {
1533 return null;
1536 $result = $pluginowner->get_file_info($browser, $filearea, $itemid, $filepath, $filename);
1537 return $result;
1541 * Prints the complete info about a user's interaction with an assignment.
1543 * @param stdClass $course
1544 * @param stdClass $user
1545 * @param stdClass $coursemodule
1546 * @param stdClass $assign the database assign record
1548 * This prints the submission summary and feedback summary for this student.
1550 function assign_user_complete($course, $user, $coursemodule, $assign) {
1551 global $CFG;
1552 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1554 $context = context_module::instance($coursemodule->id);
1556 $assignment = new assign($context, $coursemodule, $course);
1558 echo $assignment->view_student_summary($user, false);
1562 * Rescale all grades for this activity and push the new grades to the gradebook.
1564 * @param stdClass $course Course db record
1565 * @param stdClass $cm Course module db record
1566 * @param float $oldmin
1567 * @param float $oldmax
1568 * @param float $newmin
1569 * @param float $newmax
1571 function assign_rescale_activity_grades($course, $cm, $oldmin, $oldmax, $newmin, $newmax) {
1572 global $DB;
1574 if ($oldmax <= $oldmin) {
1575 // Grades cannot be scaled.
1576 return false;
1578 $scale = ($newmax - $newmin) / ($oldmax - $oldmin);
1579 if (($newmax - $newmin) <= 1) {
1580 // We would lose too much precision, lets bail.
1581 return false;
1584 $params = array(
1585 'p1' => $oldmin,
1586 'p2' => $scale,
1587 'p3' => $newmin,
1588 'a' => $cm->instance
1591 // Only rescale grades that are greater than or equal to 0. Anything else is a special value.
1592 $sql = 'UPDATE {assign_grades} set grade = (((grade - :p1) * :p2) + :p3) where assignment = :a and grade >= 0';
1593 $dbupdate = $DB->execute($sql, $params);
1594 if (!$dbupdate) {
1595 return false;
1598 // Now re-push all grades to the gradebook.
1599 $dbparams = array('id' => $cm->instance);
1600 $assign = $DB->get_record('assign', $dbparams);
1601 $assign->cmidnumber = $cm->idnumber;
1603 assign_update_grades($assign);
1605 return true;
1609 * Print the grade information for the assignment for this user.
1611 * @param stdClass $course
1612 * @param stdClass $user
1613 * @param stdClass $coursemodule
1614 * @param stdClass $assignment
1616 function assign_user_outline($course, $user, $coursemodule, $assignment) {
1617 global $CFG;
1618 require_once($CFG->libdir.'/gradelib.php');
1619 require_once($CFG->dirroot.'/grade/grading/lib.php');
1621 $gradinginfo = grade_get_grades($course->id,
1622 'mod',
1623 'assign',
1624 $assignment->id,
1625 $user->id);
1627 $gradingitem = $gradinginfo->items[0];
1628 $gradebookgrade = $gradingitem->grades[$user->id];
1630 if (empty($gradebookgrade->str_long_grade)) {
1631 return null;
1633 $result = new stdClass();
1634 $result->info = get_string('outlinegrade', 'assign', $gradebookgrade->str_long_grade);
1635 $result->time = $gradebookgrade->dategraded;
1637 return $result;
1641 * Obtains the automatic completion state for this module based on any conditions
1642 * in assign settings.
1644 * @param object $course Course
1645 * @param object $cm Course-module
1646 * @param int $userid User ID
1647 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
1648 * @return bool True if completed, false if not, $type if conditions not set.
1650 function assign_get_completion_state($course, $cm, $userid, $type) {
1651 global $CFG, $DB;
1652 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1654 $assign = new assign(null, $cm, $course);
1656 // If completion option is enabled, evaluate it and return true/false.
1657 if ($assign->get_instance()->completionsubmit) {
1658 if ($assign->get_instance()->teamsubmission) {
1659 $submission = $assign->get_group_submission($userid, 0, false);
1660 } else {
1661 $submission = $assign->get_user_submission($userid, false);
1663 return $submission && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1664 } else {
1665 // Completion option is not enabled so just return $type.
1666 return $type;
1671 * Serves intro attachment files.
1673 * @param mixed $course course or id of the course
1674 * @param mixed $cm course module or id of the course module
1675 * @param context $context
1676 * @param string $filearea
1677 * @param array $args
1678 * @param bool $forcedownload
1679 * @param array $options additional options affecting the file serving
1680 * @return bool false if file not found, does not return if found - just send the file
1682 function assign_pluginfile($course,
1683 $cm,
1684 context $context,
1685 $filearea,
1686 $args,
1687 $forcedownload,
1688 array $options=array()) {
1689 global $CFG;
1691 if ($context->contextlevel != CONTEXT_MODULE) {
1692 return false;
1695 require_login($course, false, $cm);
1696 if (!has_capability('mod/assign:view', $context)) {
1697 return false;
1700 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1701 $assign = new assign($context, $cm, $course);
1703 if ($filearea !== ASSIGN_INTROATTACHMENT_FILEAREA) {
1704 return false;
1706 if (!$assign->show_intro()) {
1707 return false;
1710 $itemid = (int)array_shift($args);
1711 if ($itemid != 0) {
1712 return false;
1715 $relativepath = implode('/', $args);
1717 $fullpath = "/{$context->id}/mod_assign/$filearea/$itemid/$relativepath";
1719 $fs = get_file_storage();
1720 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1721 return false;
1723 send_stored_file($file, 0, 0, $forcedownload, $options);
1727 * Serve the grading panel as a fragment.
1729 * @param array $args List of named arguments for the fragment loader.
1730 * @return string
1732 function mod_assign_output_fragment_gradingpanel($args) {
1733 global $CFG;
1735 $context = $args['context'];
1737 if ($context->contextlevel != CONTEXT_MODULE) {
1738 return null;
1740 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1741 $assign = new assign($context, null, null);
1743 $userid = clean_param($args['userid'], PARAM_INT);
1744 $attemptnumber = clean_param($args['attemptnumber'], PARAM_INT);
1745 $formdata = array();
1746 if (!empty($args['jsonformdata'])) {
1747 $serialiseddata = json_decode($args['jsonformdata']);
1748 parse_str($serialiseddata, $formdata);
1750 $viewargs = array(
1751 'userid' => $userid,
1752 'attemptnumber' => $attemptnumber,
1753 'formdata' => $formdata
1756 return $assign->view('gradingpanel', $viewargs);
1760 * Check if the module has any update that affects the current user since a given time.
1762 * @param cm_info $cm course module data
1763 * @param int $from the time to check updates from
1764 * @param array $filter if we need to check only specific updates
1765 * @return stdClass an object with the different type of areas indicating if they were updated or not
1766 * @since Moodle 3.2
1768 function assign_check_updates_since(cm_info $cm, $from, $filter = array()) {
1769 global $DB, $USER, $CFG;
1770 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1772 $updates = new stdClass();
1773 $updates = course_check_module_updates_since($cm, $from, array(ASSIGN_INTROATTACHMENT_FILEAREA), $filter);
1775 // Check if there is a new submission by the user or new grades.
1776 $select = 'assignment = :id AND userid = :userid AND (timecreated > :since1 OR timemodified > :since2)';
1777 $params = array('id' => $cm->instance, 'userid' => $USER->id, 'since1' => $from, 'since2' => $from);
1778 $updates->submissions = (object) array('updated' => false);
1779 $submissions = $DB->get_records_select('assign_submission', $select, $params, '', 'id');
1780 if (!empty($submissions)) {
1781 $updates->submissions->updated = true;
1782 $updates->submissions->itemids = array_keys($submissions);
1785 $updates->grades = (object) array('updated' => false);
1786 $grades = $DB->get_records_select('assign_grades', $select, $params, '', 'id');
1787 if (!empty($grades)) {
1788 $updates->grades->updated = true;
1789 $updates->grades->itemids = array_keys($grades);
1792 // Now, teachers should see other students updates.
1793 if (has_capability('mod/assign:viewgrades', $cm->context)) {
1794 $params = array('id' => $cm->instance, 'since1' => $from, 'since2' => $from);
1795 $select = 'assignment = :id AND (timecreated > :since1 OR timemodified > :since2)';
1797 if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS) {
1798 $groupusers = array_keys(groups_get_activity_shared_group_members($cm));
1799 if (empty($groupusers)) {
1800 return $updates;
1802 list($insql, $inparams) = $DB->get_in_or_equal($groupusers, SQL_PARAMS_NAMED);
1803 $select .= ' AND userid ' . $insql;
1804 $params = array_merge($params, $inparams);
1807 $updates->usersubmissions = (object) array('updated' => false);
1808 $submissions = $DB->get_records_select('assign_submission', $select, $params, '', 'id');
1809 if (!empty($submissions)) {
1810 $updates->usersubmissions->updated = true;
1811 $updates->usersubmissions->itemids = array_keys($submissions);
1814 $updates->usergrades = (object) array('updated' => false);
1815 $grades = $DB->get_records_select('assign_grades', $select, $params, '', 'id');
1816 if (!empty($grades)) {
1817 $updates->usergrades->updated = true;
1818 $updates->usergrades->itemids = array_keys($grades);
1822 return $updates;
1826 * Is the event visible?
1828 * This is used to determine global visibility of an event in all places throughout Moodle. For example,
1829 * the ASSIGN_EVENT_TYPE_GRADINGDUE event will not be shown to students on their calendar.
1831 * @param calendar_event $event
1832 * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
1833 * @return bool Returns true if the event is visible to the current user, false otherwise.
1835 function mod_assign_core_calendar_is_event_visible(calendar_event $event, $userid = 0) {
1836 global $CFG, $USER;
1838 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1840 if (empty($userid)) {
1841 $userid = $USER->id;
1844 $cm = get_fast_modinfo($event->courseid, $userid)->instances['assign'][$event->instance];
1845 $context = context_module::instance($cm->id);
1847 $assign = new assign($context, $cm, null);
1849 if ($event->eventtype == ASSIGN_EVENT_TYPE_GRADINGDUE) {
1850 return $assign->can_grade($userid);
1851 } else {
1852 return true;
1857 * This function receives a calendar event and returns the action associated with it, or null if there is none.
1859 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
1860 * is not displayed on the block.
1862 * @param calendar_event $event
1863 * @param \core_calendar\action_factory $factory
1864 * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
1865 * @return \core_calendar\local\event\entities\action_interface|null
1867 function mod_assign_core_calendar_provide_event_action(calendar_event $event,
1868 \core_calendar\action_factory $factory,
1869 $userid = 0) {
1871 global $CFG, $USER;
1873 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1875 if (empty($userid)) {
1876 $userid = $USER->id;
1879 $cm = get_fast_modinfo($event->courseid, $userid)->instances['assign'][$event->instance];
1880 $context = context_module::instance($cm->id);
1882 $assign = new assign($context, $cm, null);
1884 // Apply overrides.
1885 $assign->update_effective_access($userid);
1887 if ($event->eventtype == ASSIGN_EVENT_TYPE_GRADINGDUE) {
1888 $name = get_string('grade');
1889 $url = new \moodle_url('/mod/assign/view.php', [
1890 'id' => $cm->id,
1891 'action' => 'grader'
1893 $itemcount = $assign->count_submissions_need_grading();
1894 $actionable = $assign->can_grade($userid) && (time() >= $assign->get_instance()->allowsubmissionsfromdate);
1895 } else {
1896 $usersubmission = $assign->get_user_submission($userid, false);
1897 if ($usersubmission && $usersubmission->status === ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
1898 // The user has already submitted.
1899 // We do not want to change the text to edit the submission, we want to remove the event from the Dashboard entirely.
1900 return null;
1903 $participant = $assign->get_participant($userid);
1905 if (!$participant) {
1906 // If the user is not a participant in the assignment then they have
1907 // no action to take. This will filter out the events for teachers.
1908 return null;
1911 // The user has not yet submitted anything. Show the addsubmission link.
1912 $name = get_string('addsubmission', 'assign');
1913 $url = new \moodle_url('/mod/assign/view.php', [
1914 'id' => $cm->id,
1915 'action' => 'editsubmission'
1917 $itemcount = 1;
1918 $actionable = $assign->is_any_submission_plugin_enabled() && $assign->can_edit_submission($userid, $userid);
1921 return $factory->create_instance(
1922 $name,
1923 $url,
1924 $itemcount,
1925 $actionable
1930 * Callback function that determines whether an action event should be showing its item count
1931 * based on the event type and the item count.
1933 * @param calendar_event $event The calendar event.
1934 * @param int $itemcount The item count associated with the action event.
1935 * @return bool
1937 function mod_assign_core_calendar_event_action_shows_item_count(calendar_event $event, $itemcount = 0) {
1938 // List of event types where the action event's item count should be shown.
1939 $eventtypesshowingitemcount = [
1940 ASSIGN_EVENT_TYPE_GRADINGDUE
1942 // For mod_assign, item count should be shown if the event type is 'gradingdue' and there is one or more item count.
1943 return in_array($event->eventtype, $eventtypesshowingitemcount) && $itemcount > 0;
1947 * This function calculates the minimum and maximum cutoff values for the timestart of
1948 * the given event.
1950 * It will return an array with two values, the first being the minimum cutoff value and
1951 * the second being the maximum cutoff value. Either or both values can be null, which
1952 * indicates there is no minimum or maximum, respectively.
1954 * If a cutoff is required then the function must return an array containing the cutoff
1955 * timestamp and error string to display to the user if the cutoff value is violated.
1957 * A minimum and maximum cutoff return value will look like:
1959 * [1505704373, 'The due date must be after the sbumission start date'],
1960 * [1506741172, 'The due date must be before the cutoff date']
1963 * If the event does not have a valid timestart range then [false, false] will
1964 * be returned.
1966 * @param calendar_event $event The calendar event to get the time range for
1967 * @param stdClass $instance The module instance to get the range from
1968 * @return array
1970 function mod_assign_core_calendar_get_valid_event_timestart_range(\calendar_event $event, \stdClass $instance) {
1971 global $CFG;
1973 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1975 $courseid = $event->courseid;
1976 $modulename = $event->modulename;
1977 $instanceid = $event->instance;
1978 $coursemodule = get_fast_modinfo($courseid)->instances[$modulename][$instanceid];
1979 $context = context_module::instance($coursemodule->id);
1980 $assign = new assign($context, null, null);
1981 $assign->set_instance($instance);
1983 return $assign->get_valid_calendar_event_timestart_range($event);
1987 * This function will update the assign module according to the
1988 * event that has been modified.
1990 * @throws \moodle_exception
1991 * @param \calendar_event $event
1992 * @param stdClass $instance The module instance to get the range from
1994 function mod_assign_core_calendar_event_timestart_updated(\calendar_event $event, \stdClass $instance) {
1995 global $CFG, $DB;
1997 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1999 if (empty($event->instance) || $event->modulename != 'assign') {
2000 return;
2003 if ($instance->id != $event->instance) {
2004 return;
2007 if (!in_array($event->eventtype, [ASSIGN_EVENT_TYPE_DUE, ASSIGN_EVENT_TYPE_GRADINGDUE])) {
2008 return;
2011 $courseid = $event->courseid;
2012 $modulename = $event->modulename;
2013 $instanceid = $event->instance;
2014 $modified = false;
2015 $coursemodule = get_fast_modinfo($courseid)->instances[$modulename][$instanceid];
2016 $context = context_module::instance($coursemodule->id);
2018 // The user does not have the capability to modify this activity.
2019 if (!has_capability('moodle/course:manageactivities', $context)) {
2020 return;
2023 $assign = new assign($context, $coursemodule, null);
2024 $assign->set_instance($instance);
2026 if ($event->eventtype == ASSIGN_EVENT_TYPE_DUE) {
2027 // This check is in here because due date events are currently
2028 // the only events that can be overridden, so we can save a DB
2029 // query if we don't bother checking other events.
2030 if ($assign->is_override_calendar_event($event)) {
2031 // This is an override event so we should ignore it.
2032 return;
2035 $newduedate = $event->timestart;
2037 if ($newduedate != $instance->duedate) {
2038 $instance->duedate = $newduedate;
2039 $modified = true;
2041 } else if ($event->eventtype == ASSIGN_EVENT_TYPE_GRADINGDUE) {
2042 $newduedate = $event->timestart;
2044 if ($newduedate != $instance->gradingduedate) {
2045 $instance->gradingduedate = $newduedate;
2046 $modified = true;
2050 if ($modified) {
2051 $instance->timemodified = time();
2052 // Persist the assign instance changes.
2053 $DB->update_record('assign', $instance);
2054 $assign->update_calendar($coursemodule->id);
2055 $event = \core\event\course_module_updated::create_from_cm($coursemodule, $context);
2056 $event->trigger();