MDL-36233 mod_assign: fixed submission time comparison sql and test.
[moodle.git] / mod / assign / lib.php
blob81f13c9a834809a203bbc41a09f72e52c5094db2
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 * @return bool
99 function assign_refresh_events($courseid = 0) {
100 global $CFG, $DB;
101 require_once($CFG->dirroot . '/mod/assign/locallib.php');
103 if ($courseid) {
104 // Make sure that the course id is numeric.
105 if (!is_numeric($courseid)) {
106 return false;
108 if (!$assigns = $DB->get_records('assign', array('course' => $courseid))) {
109 return false;
111 // Get course from courseid parameter.
112 if (!$course = $DB->get_record('course', array('id' => $courseid), '*')) {
113 return false;
115 } else {
116 if (!$assigns = $DB->get_records('assign')) {
117 return false;
120 foreach ($assigns as $assign) {
121 // Use assignment's course column if courseid parameter is not given.
122 if (!$courseid) {
123 $courseid = $assign->course;
124 if (!$course = $DB->get_record('course', array('id' => $courseid), '*')) {
125 continue;
128 if (!$cm = get_coursemodule_from_instance('assign', $assign->id, $courseid, false)) {
129 continue;
131 $context = context_module::instance($cm->id);
132 $assignment = new assign($context, $cm, $course);
133 $assignment->update_calendar($cm->id);
136 return true;
140 * Removes all grades from gradebook
142 * @param int $courseid The ID of the course to reset
143 * @param string $type Optional type of assignment to limit the reset to a particular assignment type
145 function assign_reset_gradebook($courseid, $type='') {
146 global $CFG, $DB;
148 $params = array('moduletype'=>'assign', 'courseid'=>$courseid);
149 $sql = 'SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
150 FROM {assign} a, {course_modules} cm, {modules} m
151 WHERE m.name=:moduletype AND m.id=cm.module AND cm.instance=a.id AND a.course=:courseid';
153 if ($assignments = $DB->get_records_sql($sql, $params)) {
154 foreach ($assignments as $assignment) {
155 assign_grade_item_update($assignment, 'reset');
161 * Implementation of the function for printing the form elements that control
162 * whether the course reset functionality affects the assignment.
163 * @param moodleform $mform form passed by reference
165 function assign_reset_course_form_definition(&$mform) {
166 $mform->addElement('header', 'assignheader', get_string('modulenameplural', 'assign'));
167 $name = get_string('deleteallsubmissions', 'assign');
168 $mform->addElement('advcheckbox', 'reset_assign_submissions', $name);
169 $mform->addElement('advcheckbox', 'reset_assign_user_overrides',
170 get_string('removealluseroverrides', 'assign'));
171 $mform->addElement('advcheckbox', 'reset_assign_group_overrides',
172 get_string('removeallgroupoverrides', 'assign'));
176 * Course reset form defaults.
177 * @param object $course
178 * @return array
180 function assign_reset_course_form_defaults($course) {
181 return array('reset_assign_submissions' => 1,
182 'reset_assign_group_overrides' => 1,
183 'reset_assign_user_overrides' => 1);
187 * Update an assignment instance
189 * This is done by calling the update_instance() method of the assignment type class
190 * @param stdClass $data
191 * @param stdClass $form - unused
192 * @return object
194 function assign_update_instance(stdClass $data, $form) {
195 global $CFG;
196 require_once($CFG->dirroot . '/mod/assign/locallib.php');
197 $context = context_module::instance($data->coursemodule);
198 $assignment = new assign($context, null, null);
199 return $assignment->update_instance($data);
203 * This function updates the events associated to the assign.
204 * If $override is non-zero, then it updates only the events
205 * associated with the specified override.
207 * @uses ASSIGN_MAX_EVENT_LENGTH
208 * @param object $assign the assign object.
209 * @param object $override (optional) limit to a specific override
211 function assign_update_events($assign, $override = null) {
212 global $CFG, $DB;
214 require_once($CFG->dirroot . '/calendar/lib.php');
216 // Load the old events relating to this assign.
217 $conds = array('modulename' => 'assign',
218 'instance' => $assign->get_context()->id);
219 if (!empty($override)) {
220 // Only load events for this override.
221 if (isset($override->userid)) {
222 $conds['userid'] = $override->userid;
223 } else {
224 $conds['groupid'] = $override->groupid;
227 $oldevents = $DB->get_records('event', $conds);
229 // Now make a todo list of all that needs to be updated.
230 if (empty($override)) {
231 // We are updating the primary settings for the assign, so we
232 // need to add all the overrides.
233 $overrides = $DB->get_records('assign_overrides', array('assignid' => $assign->id));
234 // As well as the original assign (empty override).
235 $overrides[] = new stdClass();
236 } else {
237 // Just do the one override.
238 $overrides = array($override);
241 foreach ($overrides as $current) {
242 $groupid = isset($current->groupid) ? $current->groupid : 0;
243 $userid = isset($current->userid) ? $current->userid : 0;
244 $allowsubmissionsfromdate = isset($current->allowsubmissionsfromdate
245 ) ? $current->allowsubmissionsfromdate : $assign->get_context()->allowsubmissionsfromdate;
246 $duedate = isset($current->duedate) ? $current->duedate : $assign->get_context()->duedate;
248 // Only add open/close events for an override if they differ from the assign default.
249 $addopen = empty($current->id) || !empty($current->allowsubmissionsfromdate);
250 $addclose = empty($current->id) || !empty($current->duedate);
252 if (!empty($assign->coursemodule)) {
253 $cmid = $assign->coursemodule;
254 } else {
255 $cmid = get_coursemodule_from_instance('assign', $assign->get_context()->id, $assign->get_context()->course)->id;
258 $event = new stdClass();
259 $event->description = format_module_intro('assign', $assign->get_context(), $cmid);
260 // Events module won't show user events when the courseid is nonzero.
261 $event->courseid = ($userid) ? 0 : $assign->get_context()->course;
262 $event->groupid = $groupid;
263 $event->userid = $userid;
264 $event->modulename = 'assign';
265 $event->instance = $assign->get_context()->id;
266 $event->timestart = $allowsubmissionsfromdate;
267 $event->timeduration = max($duedate - $allowsubmissionsfromdate, 0);
268 $event->visible = instance_is_visible('assign', $assign);
269 $event->eventtype = 'open';
271 // Determine the event name.
272 if ($groupid) {
273 $params = new stdClass();
274 $params->assign = $assign->get_context()->name;
275 $params->group = groups_get_group_name($groupid);
276 if ($params->group === false) {
277 // Group doesn't exist, just skip it.
278 continue;
280 $eventname = get_string('overridegroupeventname', 'assign', $params);
281 } else if ($userid) {
282 $params = new stdClass();
283 $params->assign = $assign->get_context()->name;
284 $eventname = get_string('overrideusereventname', 'assign', $params);
285 } else {
286 $eventname = $assign->name;
288 if ($addopen or $addclose) {
289 if ($duedate and $allowsubmissionsfromdate and $event->timeduration <= ASSIGN_MAX_EVENT_LENGTH) {
290 // Single event for the whole assign.
291 if ($oldevent = array_shift($oldevents)) {
292 $event->id = $oldevent->id;
293 } else {
294 unset($event->id);
296 $event->name = $eventname;
297 // The method calendar_event::create will reuse a db record if the id field is set.
298 calendar_event::create($event);
299 } else {
300 // Separate start and end events.
301 $event->timeduration = 0;
302 if ($allowsubmissionsfromdate && $addopen) {
303 if ($oldevent = array_shift($oldevents)) {
304 $event->id = $oldevent->id;
305 } else {
306 unset($event->id);
308 $event->name = $eventname.' ('.get_string('open', 'assign').')';
309 // The method calendar_event::create will reuse a db record if the id field is set.
310 calendar_event::create($event);
312 if ($duedate && $addclose) {
313 if ($oldevent = array_shift($oldevents)) {
314 $event->id = $oldevent->id;
315 } else {
316 unset($event->id);
318 $event->name = $eventname.' ('.get_string('duedate', 'assign').')';
319 $event->timestart = $duedate;
320 $event->eventtype = 'close';
321 calendar_event::create($event);
327 // Delete any leftover events.
328 foreach ($oldevents as $badevent) {
329 $badevent = calendar_event::load($badevent);
330 $badevent->delete();
335 * Return the list if Moodle features this module supports
337 * @param string $feature FEATURE_xx constant for requested feature
338 * @return mixed True if module supports feature, null if doesn't know
340 function assign_supports($feature) {
341 switch($feature) {
342 case FEATURE_GROUPS:
343 return true;
344 case FEATURE_GROUPINGS:
345 return true;
346 case FEATURE_MOD_INTRO:
347 return true;
348 case FEATURE_COMPLETION_TRACKS_VIEWS:
349 return true;
350 case FEATURE_COMPLETION_HAS_RULES:
351 return true;
352 case FEATURE_GRADE_HAS_GRADE:
353 return true;
354 case FEATURE_GRADE_OUTCOMES:
355 return true;
356 case FEATURE_BACKUP_MOODLE2:
357 return true;
358 case FEATURE_SHOW_DESCRIPTION:
359 return true;
360 case FEATURE_ADVANCED_GRADING:
361 return true;
362 case FEATURE_PLAGIARISM:
363 return true;
364 case FEATURE_COMMENT:
365 return true;
367 default:
368 return null;
373 * Lists all gradable areas for the advanced grading methods gramework
375 * @return array('string'=>'string') An array with area names as keys and descriptions as values
377 function assign_grading_areas_list() {
378 return array('submissions'=>get_string('submissions', 'assign'));
383 * extend an assigment navigation settings
385 * @param settings_navigation $settings
386 * @param navigation_node $navref
387 * @return void
389 function assign_extend_settings_navigation(settings_navigation $settings, navigation_node $navref) {
390 global $PAGE, $DB;
392 // We want to add these new nodes after the Edit settings node, and before the
393 // Locally assigned roles node. Of course, both of those are controlled by capabilities.
394 $keys = $navref->get_children_key_list();
395 $beforekey = null;
396 $i = array_search('modedit', $keys);
397 if ($i === false and array_key_exists(0, $keys)) {
398 $beforekey = $keys[0];
399 } else if (array_key_exists($i + 1, $keys)) {
400 $beforekey = $keys[$i + 1];
403 $cm = $PAGE->cm;
404 if (!$cm) {
405 return;
408 $context = $cm->context;
409 $course = $PAGE->course;
411 if (!$course) {
412 return;
415 if (has_capability('mod/assign:manageoverrides', $PAGE->cm->context)) {
416 $url = new moodle_url('/mod/assign/overrides.php', array('cmid' => $PAGE->cm->id));
417 $node = navigation_node::create(get_string('groupoverrides', 'assign'),
418 new moodle_url($url, array('mode' => 'group')),
419 navigation_node::TYPE_SETTING, null, 'mod_assign_groupoverrides');
420 $navref->add_node($node, $beforekey);
422 $node = navigation_node::create(get_string('useroverrides', 'assign'),
423 new moodle_url($url, array('mode' => 'user')),
424 navigation_node::TYPE_SETTING, null, 'mod_assign_useroverrides');
425 $navref->add_node($node, $beforekey);
428 // Link to gradebook.
429 if (has_capability('gradereport/grader:view', $cm->context) &&
430 has_capability('moodle/grade:viewall', $cm->context)) {
431 $link = new moodle_url('/grade/report/grader/index.php', array('id' => $course->id));
432 $linkname = get_string('viewgradebook', 'assign');
433 $node = $navref->add($linkname, $link, navigation_node::TYPE_SETTING);
436 // Link to download all submissions.
437 if (has_any_capability(array('mod/assign:grade', 'mod/assign:viewgrades'), $context)) {
438 $link = new moodle_url('/mod/assign/view.php', array('id' => $cm->id, 'action'=>'grading'));
439 $node = $navref->add(get_string('viewgrading', 'assign'), $link, navigation_node::TYPE_SETTING);
441 $link = new moodle_url('/mod/assign/view.php', array('id' => $cm->id, 'action'=>'downloadall'));
442 $node = $navref->add(get_string('downloadall', 'assign'), $link, navigation_node::TYPE_SETTING);
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 $CFG, $DB;
472 $dbparams = array('id'=>$coursemodule->instance);
473 $fields = 'id, name, alwaysshowdescription, allowsubmissionsfromdate, intro, introformat';
474 if (! $assignment = $DB->get_record('assign', $dbparams, $fields)) {
475 return false;
478 $result = new cached_cm_info();
479 $result->name = $assignment->name;
480 if ($coursemodule->showdescription) {
481 if ($assignment->alwaysshowdescription || time() > $assignment->allowsubmissionsfromdate) {
482 // Convert intro to html. Do not filter cached version, filters run at display time.
483 $result->content = format_module_intro('assign', $assignment, $coursemodule->id, false);
486 return $result;
490 * Return a list of page types
491 * @param string $pagetype current page type
492 * @param stdClass $parentcontext Block's parent context
493 * @param stdClass $currentcontext Current context of block
495 function assign_page_type_list($pagetype, $parentcontext, $currentcontext) {
496 $modulepagetype = array(
497 'mod-assign-*' => get_string('page-mod-assign-x', 'assign'),
498 'mod-assign-view' => get_string('page-mod-assign-view', 'assign'),
500 return $modulepagetype;
504 * Print an overview of all assignments
505 * for the courses.
507 * @param mixed $courses The list of courses to print the overview for
508 * @param array $htmlarray The array of html to return
510 * @return true
512 function assign_print_overview($courses, &$htmlarray) {
513 global $CFG, $DB;
515 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
516 return true;
519 if (!$assignments = get_all_instances_in_courses('assign', $courses)) {
520 return true;
523 $assignmentids = array();
525 // Do assignment_base::isopen() here without loading the whole thing for speed.
526 foreach ($assignments as $key => $assignment) {
527 $time = time();
528 $isopen = false;
529 if ($assignment->duedate) {
530 $duedate = false;
531 if ($assignment->cutoffdate) {
532 $duedate = $assignment->cutoffdate;
534 if ($duedate) {
535 $isopen = ($assignment->allowsubmissionsfromdate <= $time && $time <= $duedate);
536 } else {
537 $isopen = ($assignment->allowsubmissionsfromdate <= $time);
540 if ($isopen) {
541 $assignmentids[] = $assignment->id;
545 if (empty($assignmentids)) {
546 // No assignments to look at - we're done.
547 return true;
550 // Definitely something to print, now include the constants we need.
551 require_once($CFG->dirroot . '/mod/assign/locallib.php');
553 $strduedate = get_string('duedate', 'assign');
554 $strcutoffdate = get_string('nosubmissionsacceptedafter', 'assign');
555 $strnolatesubmissions = get_string('nolatesubmissions', 'assign');
556 $strduedateno = get_string('duedateno', 'assign');
557 $strassignment = get_string('modulename', 'assign');
559 // We do all possible database work here *outside* of the loop to ensure this scales.
560 list($sqlassignmentids, $assignmentidparams) = $DB->get_in_or_equal($assignmentids);
562 $mysubmissions = null;
563 $unmarkedsubmissions = null;
565 foreach ($assignments as $assignment) {
567 // Do not show assignments that are not open.
568 if (!in_array($assignment->id, $assignmentids)) {
569 continue;
572 $context = context_module::instance($assignment->coursemodule);
574 // Does the submission status of the assignment require notification?
575 if (has_capability('mod/assign:submit', $context, null, false)) {
576 // Does the submission status of the assignment require notification?
577 $submitdetails = assign_get_mysubmission_details_for_print_overview($mysubmissions, $sqlassignmentids,
578 $assignmentidparams, $assignment);
579 } else {
580 $submitdetails = false;
583 if (has_capability('mod/assign:grade', $context, null, false)) {
584 // Does the grading status of the assignment require notification ?
585 $gradedetails = assign_get_grade_details_for_print_overview($unmarkedsubmissions, $sqlassignmentids,
586 $assignmentidparams, $assignment, $context);
587 } else {
588 $gradedetails = false;
591 if (empty($submitdetails) && empty($gradedetails)) {
592 // There is no need to display this assignment as there is nothing to notify.
593 continue;
596 $dimmedclass = '';
597 if (!$assignment->visible) {
598 $dimmedclass = ' class="dimmed"';
600 $href = $CFG->wwwroot . '/mod/assign/view.php?id=' . $assignment->coursemodule;
601 $basestr = '<div class="assign overview">' .
602 '<div class="name">' .
603 $strassignment . ': '.
604 '<a ' . $dimmedclass .
605 'title="' . $strassignment . '" ' .
606 'href="' . $href . '">' .
607 format_string($assignment->name) .
608 '</a></div>';
609 if ($assignment->duedate) {
610 $userdate = userdate($assignment->duedate);
611 $basestr .= '<div class="info">' . $strduedate . ': ' . $userdate . '</div>';
612 } else {
613 $basestr .= '<div class="info">' . $strduedateno . '</div>';
615 if ($assignment->cutoffdate) {
616 if ($assignment->cutoffdate == $assignment->duedate) {
617 $basestr .= '<div class="info">' . $strnolatesubmissions . '</div>';
618 } else {
619 $userdate = userdate($assignment->cutoffdate);
620 $basestr .= '<div class="info">' . $strcutoffdate . ': ' . $userdate . '</div>';
624 // Show only relevant information.
625 if (!empty($submitdetails)) {
626 $basestr .= $submitdetails;
629 if (!empty($gradedetails)) {
630 $basestr .= $gradedetails;
632 $basestr .= '</div>';
634 if (empty($htmlarray[$assignment->course]['assign'])) {
635 $htmlarray[$assignment->course]['assign'] = $basestr;
636 } else {
637 $htmlarray[$assignment->course]['assign'] .= $basestr;
640 return true;
644 * This api generates html to be displayed to students in print overview section, related to their submission status of the given
645 * assignment.
647 * @param array $mysubmissions list of submissions of current user indexed by assignment id.
648 * @param string $sqlassignmentids sql clause used to filter open assignments.
649 * @param array $assignmentidparams sql params used to filter open assignments.
650 * @param stdClass $assignment current assignment
652 * @return bool|string html to display , false if nothing needs to be displayed.
653 * @throws coding_exception
655 function assign_get_mysubmission_details_for_print_overview(&$mysubmissions, $sqlassignmentids, $assignmentidparams,
656 $assignment) {
657 global $USER, $DB;
659 if ($assignment->nosubmissions) {
660 // Offline assignment. No need to display alerts for offline assignments.
661 return false;
664 $strnotsubmittedyet = get_string('notsubmittedyet', 'assign');
666 if (!isset($mysubmissions)) {
668 // Get all user submissions, indexed by assignment id.
669 $dbparams = array_merge(array($USER->id), $assignmentidparams, array($USER->id));
670 $mysubmissions = $DB->get_records_sql('SELECT a.id AS assignment,
671 a.nosubmissions AS nosubmissions,
672 g.timemodified AS timemarked,
673 g.grader AS grader,
674 g.grade AS grade,
675 s.status AS status
676 FROM {assign} a, {assign_submission} s
677 LEFT JOIN {assign_grades} g ON
678 g.assignment = s.assignment AND
679 g.userid = ? AND
680 g.attemptnumber = s.attemptnumber
681 WHERE a.id ' . $sqlassignmentids . ' AND
682 s.latest = 1 AND
683 s.assignment = a.id AND
684 s.userid = ?', $dbparams);
687 $submitdetails = '';
688 $submitdetails .= '<div class="details">';
689 $submitdetails .= get_string('mysubmission', 'assign');
690 $submission = false;
692 if (isset($mysubmissions[$assignment->id])) {
693 $submission = $mysubmissions[$assignment->id];
696 if ($submission && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
697 // A valid submission already exists, no need to notify students about this.
698 return false;
701 // We need to show details only if a valid submission doesn't exist.
702 if (!$submission ||
703 !$submission->status ||
704 $submission->status == ASSIGN_SUBMISSION_STATUS_DRAFT ||
705 $submission->status == ASSIGN_SUBMISSION_STATUS_NEW
707 $submitdetails .= $strnotsubmittedyet;
708 } else {
709 $submitdetails .= get_string('submissionstatus_' . $submission->status, 'assign');
711 if ($assignment->markingworkflow) {
712 $workflowstate = $DB->get_field('assign_user_flags', 'workflowstate', array('assignment' =>
713 $assignment->id, 'userid' => $USER->id));
714 if ($workflowstate) {
715 $gradingstatus = 'markingworkflowstate' . $workflowstate;
716 } else {
717 $gradingstatus = 'markingworkflowstate' . ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED;
719 } else if (!empty($submission->grade) && $submission->grade !== null && $submission->grade >= 0) {
720 $gradingstatus = ASSIGN_GRADING_STATUS_GRADED;
721 } else {
722 $gradingstatus = ASSIGN_GRADING_STATUS_NOT_GRADED;
724 $submitdetails .= ', ' . get_string($gradingstatus, 'assign');
725 $submitdetails .= '</div>';
726 return $submitdetails;
730 * This api generates html to be displayed to teachers in print overview section, related to the grading status of the given
731 * assignment's submissions.
733 * @param array $unmarkedsubmissions list of submissions of that are currently unmarked indexed by assignment id.
734 * @param string $sqlassignmentids sql clause used to filter open assignments.
735 * @param array $assignmentidparams sql params used to filter open assignments.
736 * @param stdClass $assignment current assignment
737 * @param context $context context of the assignment.
739 * @return bool|string html to display , false if nothing needs to be displayed.
740 * @throws coding_exception
742 function assign_get_grade_details_for_print_overview(&$unmarkedsubmissions, $sqlassignmentids, $assignmentidparams,
743 $assignment, $context) {
744 global $DB;
745 if (!isset($unmarkedsubmissions)) {
746 // Build up and array of unmarked submissions indexed by assignment id/ userid
747 // for use where the user has grading rights on assignment.
748 $dbparams = array_merge(array(ASSIGN_SUBMISSION_STATUS_SUBMITTED), $assignmentidparams);
749 $rs = $DB->get_recordset_sql('SELECT s.assignment as assignment,
750 s.userid as userid,
751 s.id as id,
752 s.status as status,
753 g.timemodified as timegraded
754 FROM {assign_submission} s
755 LEFT JOIN {assign_grades} g ON
756 s.userid = g.userid AND
757 s.assignment = g.assignment AND
758 g.attemptnumber = s.attemptnumber
759 WHERE
760 ( g.timemodified is NULL OR
761 s.timemodified >= g.timemodified OR
762 g.grade IS NULL ) AND
763 s.timemodified IS NOT NULL AND
764 s.status = ? AND
765 s.latest = 1 AND
766 s.assignment ' . $sqlassignmentids, $dbparams);
768 $unmarkedsubmissions = array();
769 foreach ($rs as $rd) {
770 $unmarkedsubmissions[$rd->assignment][$rd->userid] = $rd->id;
772 $rs->close();
775 // Count how many people can submit.
776 $submissions = 0;
777 if ($students = get_enrolled_users($context, 'mod/assign:view', 0, 'u.id')) {
778 foreach ($students as $student) {
779 if (isset($unmarkedsubmissions[$assignment->id][$student->id])) {
780 $submissions++;
785 if ($submissions) {
786 $urlparams = array('id' => $assignment->coursemodule, 'action' => 'grading');
787 $url = new moodle_url('/mod/assign/view.php', $urlparams);
788 $gradedetails = '<div class="details">' .
789 '<a href="' . $url . '">' .
790 get_string('submissionsnotgraded', 'assign', $submissions) .
791 '</a></div>';
792 return $gradedetails;
793 } else {
794 return false;
800 * Print recent activity from all assignments in a given course
802 * This is used by the recent activity block
803 * @param mixed $course the course to print activity for
804 * @param bool $viewfullnames boolean to determine whether to show full names or not
805 * @param int $timestart the time the rendering started
806 * @return bool true if activity was printed, false otherwise.
808 function assign_print_recent_activity($course, $viewfullnames, $timestart) {
809 global $CFG, $USER, $DB, $OUTPUT;
810 require_once($CFG->dirroot . '/mod/assign/locallib.php');
812 // Do not use log table if possible, it may be huge.
814 $dbparams = array($timestart, $course->id, 'assign', ASSIGN_SUBMISSION_STATUS_SUBMITTED);
815 $namefields = user_picture::fields('u', null, 'userid');
816 if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, um.id as recordid,
817 $namefields
818 FROM {assign_submission} asb
819 JOIN {assign} a ON a.id = asb.assignment
820 JOIN {course_modules} cm ON cm.instance = a.id
821 JOIN {modules} md ON md.id = cm.module
822 JOIN {user} u ON u.id = asb.userid
823 LEFT JOIN {assign_user_mapping} um ON um.userid = u.id AND um.assignment = a.id
824 WHERE asb.timemodified > ? AND
825 asb.latest = 1 AND
826 a.course = ? AND
827 md.name = ? AND
828 asb.status = ?
829 ORDER BY asb.timemodified ASC", $dbparams)) {
830 return false;
833 $modinfo = get_fast_modinfo($course);
834 $show = array();
835 $grader = array();
837 $showrecentsubmissions = get_config('assign', 'showrecentsubmissions');
839 foreach ($submissions as $submission) {
840 if (!array_key_exists($submission->cmid, $modinfo->get_cms())) {
841 continue;
843 $cm = $modinfo->get_cm($submission->cmid);
844 if (!$cm->uservisible) {
845 continue;
847 if ($submission->userid == $USER->id) {
848 $show[] = $submission;
849 continue;
852 $context = context_module::instance($submission->cmid);
853 // The act of submitting of assignment may be considered private -
854 // only graders will see it if specified.
855 if (empty($showrecentsubmissions)) {
856 if (!array_key_exists($cm->id, $grader)) {
857 $grader[$cm->id] = has_capability('moodle/grade:viewall', $context);
859 if (!$grader[$cm->id]) {
860 continue;
864 $groupmode = groups_get_activity_groupmode($cm, $course);
866 if ($groupmode == SEPARATEGROUPS &&
867 !has_capability('moodle/site:accessallgroups', $context)) {
868 if (isguestuser()) {
869 // Shortcut - guest user does not belong into any group.
870 continue;
873 // This will be slow - show only users that share group with me in this cm.
874 if (!$modinfo->get_groups($cm->groupingid)) {
875 continue;
877 $usersgroups = groups_get_all_groups($course->id, $submission->userid, $cm->groupingid);
878 if (is_array($usersgroups)) {
879 $usersgroups = array_keys($usersgroups);
880 $intersect = array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid));
881 if (empty($intersect)) {
882 continue;
886 $show[] = $submission;
889 if (empty($show)) {
890 return false;
893 echo $OUTPUT->heading(get_string('newsubmissions', 'assign').':', 3);
895 foreach ($show as $submission) {
896 $cm = $modinfo->get_cm($submission->cmid);
897 $context = context_module::instance($submission->cmid);
898 $assign = new assign($context, $cm, $cm->course);
899 $link = $CFG->wwwroot.'/mod/assign/view.php?id='.$cm->id;
900 // Obscure first and last name if blind marking enabled.
901 if ($assign->is_blind_marking()) {
902 $submission->firstname = get_string('participant', 'mod_assign');
903 if (empty($submission->recordid)) {
904 $submission->recordid = $assign->get_uniqueid_for_user($submission->userid);
906 $submission->lastname = $submission->recordid;
908 print_recent_activity_note($submission->timemodified,
909 $submission,
910 $cm->name,
911 $link,
912 false,
913 $viewfullnames);
916 return true;
920 * Returns all assignments since a given time.
922 * @param array $activities The activity information is returned in this array
923 * @param int $index The current index in the activities array
924 * @param int $timestart The earliest activity to show
925 * @param int $courseid Limit the search to this course
926 * @param int $cmid The course module id
927 * @param int $userid Optional user id
928 * @param int $groupid Optional group id
929 * @return void
931 function assign_get_recent_mod_activity(&$activities,
932 &$index,
933 $timestart,
934 $courseid,
935 $cmid,
936 $userid=0,
937 $groupid=0) {
938 global $CFG, $COURSE, $USER, $DB;
940 require_once($CFG->dirroot . '/mod/assign/locallib.php');
942 if ($COURSE->id == $courseid) {
943 $course = $COURSE;
944 } else {
945 $course = $DB->get_record('course', array('id'=>$courseid));
948 $modinfo = get_fast_modinfo($course);
950 $cm = $modinfo->get_cm($cmid);
951 $params = array();
952 if ($userid) {
953 $userselect = 'AND u.id = :userid';
954 $params['userid'] = $userid;
955 } else {
956 $userselect = '';
959 if ($groupid) {
960 $groupselect = 'AND gm.groupid = :groupid';
961 $groupjoin = 'JOIN {groups_members} gm ON gm.userid=u.id';
962 $params['groupid'] = $groupid;
963 } else {
964 $groupselect = '';
965 $groupjoin = '';
968 $params['cminstance'] = $cm->instance;
969 $params['timestart'] = $timestart;
970 $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
972 $userfields = user_picture::fields('u', null, 'userid');
974 if (!$submissions = $DB->get_records_sql('SELECT asb.id, asb.timemodified, ' .
975 $userfields .
976 ' FROM {assign_submission} asb
977 JOIN {assign} a ON a.id = asb.assignment
978 JOIN {user} u ON u.id = asb.userid ' .
979 $groupjoin .
980 ' WHERE asb.timemodified > :timestart AND
981 asb.status = :submitted AND
982 a.id = :cminstance
983 ' . $userselect . ' ' . $groupselect .
984 ' ORDER BY asb.timemodified ASC', $params)) {
985 return;
988 $groupmode = groups_get_activity_groupmode($cm, $course);
989 $cmcontext = context_module::instance($cm->id);
990 $grader = has_capability('moodle/grade:viewall', $cmcontext);
991 $accessallgroups = has_capability('moodle/site:accessallgroups', $cmcontext);
992 $viewfullnames = has_capability('moodle/site:viewfullnames', $cmcontext);
995 $showrecentsubmissions = get_config('assign', 'showrecentsubmissions');
996 $show = array();
997 foreach ($submissions as $submission) {
998 if ($submission->userid == $USER->id) {
999 $show[] = $submission;
1000 continue;
1002 // The act of submitting of assignment may be considered private -
1003 // only graders will see it if specified.
1004 if (empty($showrecentsubmissions)) {
1005 if (!$grader) {
1006 continue;
1010 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
1011 if (isguestuser()) {
1012 // Shortcut - guest user does not belong into any group.
1013 continue;
1016 // This will be slow - show only users that share group with me in this cm.
1017 if (!$modinfo->get_groups($cm->groupingid)) {
1018 continue;
1020 $usersgroups = groups_get_all_groups($course->id, $submission->userid, $cm->groupingid);
1021 if (is_array($usersgroups)) {
1022 $usersgroups = array_keys($usersgroups);
1023 $intersect = array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid));
1024 if (empty($intersect)) {
1025 continue;
1029 $show[] = $submission;
1032 if (empty($show)) {
1033 return;
1036 if ($grader) {
1037 require_once($CFG->libdir.'/gradelib.php');
1038 $userids = array();
1039 foreach ($show as $id => $submission) {
1040 $userids[] = $submission->userid;
1042 $grades = grade_get_grades($courseid, 'mod', 'assign', $cm->instance, $userids);
1045 $aname = format_string($cm->name, true);
1046 foreach ($show as $submission) {
1047 $activity = new stdClass();
1049 $activity->type = 'assign';
1050 $activity->cmid = $cm->id;
1051 $activity->name = $aname;
1052 $activity->sectionnum = $cm->sectionnum;
1053 $activity->timestamp = $submission->timemodified;
1054 $activity->user = new stdClass();
1055 if ($grader) {
1056 $activity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
1059 $userfields = explode(',', user_picture::fields());
1060 foreach ($userfields as $userfield) {
1061 if ($userfield == 'id') {
1062 // Aliased in SQL above.
1063 $activity->user->{$userfield} = $submission->userid;
1064 } else {
1065 $activity->user->{$userfield} = $submission->{$userfield};
1068 $activity->user->fullname = fullname($submission, $viewfullnames);
1070 $activities[$index++] = $activity;
1073 return;
1077 * Print recent activity from all assignments in a given course
1079 * This is used by course/recent.php
1080 * @param stdClass $activity
1081 * @param int $courseid
1082 * @param bool $detail
1083 * @param array $modnames
1085 function assign_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
1086 global $CFG, $OUTPUT;
1088 echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
1090 echo '<tr><td class="userpicture" valign="top">';
1091 echo $OUTPUT->user_picture($activity->user);
1092 echo '</td><td>';
1094 if ($detail) {
1095 $modname = $modnames[$activity->type];
1096 echo '<div class="title">';
1097 echo '<img src="' . $OUTPUT->pix_url('icon', 'assign') . '" '.
1098 'class="icon" alt="' . $modname . '">';
1099 echo '<a href="' . $CFG->wwwroot . '/mod/assign/view.php?id=' . $activity->cmid . '">';
1100 echo $activity->name;
1101 echo '</a>';
1102 echo '</div>';
1105 if (isset($activity->grade)) {
1106 echo '<div class="grade">';
1107 echo get_string('grade').': ';
1108 echo $activity->grade;
1109 echo '</div>';
1112 echo '<div class="user">';
1113 echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->id}&amp;course=$courseid\">";
1114 echo "{$activity->user->fullname}</a> - " . userdate($activity->timestamp);
1115 echo '</div>';
1117 echo '</td></tr></table>';
1121 * Checks if a scale is being used by an assignment.
1123 * This is used by the backup code to decide whether to back up a scale
1124 * @param int $assignmentid
1125 * @param int $scaleid
1126 * @return boolean True if the scale is used by the assignment
1128 function assign_scale_used($assignmentid, $scaleid) {
1129 global $DB;
1131 $return = false;
1132 $rec = $DB->get_record('assign', array('id'=>$assignmentid, 'grade'=>-$scaleid));
1134 if (!empty($rec) && !empty($scaleid)) {
1135 $return = true;
1138 return $return;
1142 * Checks if scale is being used by any instance of assignment
1144 * This is used to find out if scale used anywhere
1145 * @param int $scaleid
1146 * @return boolean True if the scale is used by any assignment
1148 function assign_scale_used_anywhere($scaleid) {
1149 global $DB;
1151 if ($scaleid and $DB->record_exists('assign', array('grade'=>-$scaleid))) {
1152 return true;
1153 } else {
1154 return false;
1159 * List the actions that correspond to a view of this module.
1160 * This is used by the participation report.
1162 * Note: This is not used by new logging system. Event with
1163 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
1164 * be considered as view action.
1166 * @return array
1168 function assign_get_view_actions() {
1169 return array('view submission', 'view feedback');
1173 * List the actions that correspond to a post of this module.
1174 * This is used by the participation report.
1176 * Note: This is not used by new logging system. Event with
1177 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
1178 * will be considered as post action.
1180 * @return array
1182 function assign_get_post_actions() {
1183 return array('upload', 'submit', 'submit for grading');
1187 * Call cron on the assign module.
1189 function assign_cron() {
1190 global $CFG;
1192 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1193 assign::cron();
1195 $plugins = core_component::get_plugin_list('assignsubmission');
1197 foreach ($plugins as $name => $plugin) {
1198 $disabled = get_config('assignsubmission_' . $name, 'disabled');
1199 if (!$disabled) {
1200 $class = 'assign_submission_' . $name;
1201 require_once($CFG->dirroot . '/mod/assign/submission/' . $name . '/locallib.php');
1202 $class::cron();
1205 $plugins = core_component::get_plugin_list('assignfeedback');
1207 foreach ($plugins as $name => $plugin) {
1208 $disabled = get_config('assignfeedback_' . $name, 'disabled');
1209 if (!$disabled) {
1210 $class = 'assign_feedback_' . $name;
1211 require_once($CFG->dirroot . '/mod/assign/feedback/' . $name . '/locallib.php');
1212 $class::cron();
1216 return true;
1220 * Returns all other capabilities used by this module.
1221 * @return array Array of capability strings
1223 function assign_get_extra_capabilities() {
1224 return array('gradereport/grader:view',
1225 'moodle/grade:viewall',
1226 'moodle/site:viewfullnames',
1227 'moodle/site:config');
1231 * Create grade item for given assignment.
1233 * @param stdClass $assign record with extra cmidnumber
1234 * @param array $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
1235 * @return int 0 if ok, error code otherwise
1237 function assign_grade_item_update($assign, $grades=null) {
1238 global $CFG;
1239 require_once($CFG->libdir.'/gradelib.php');
1241 if (!isset($assign->courseid)) {
1242 $assign->courseid = $assign->course;
1245 $params = array('itemname'=>$assign->name, 'idnumber'=>$assign->cmidnumber);
1247 // Check if feedback plugin for gradebook is enabled, if yes then
1248 // gradetype = GRADE_TYPE_TEXT else GRADE_TYPE_NONE.
1249 $gradefeedbackenabled = false;
1251 if (isset($assign->gradefeedbackenabled)) {
1252 $gradefeedbackenabled = $assign->gradefeedbackenabled;
1253 } else if ($assign->grade == 0) { // Grade feedback is needed only when grade == 0.
1254 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1255 $mod = get_coursemodule_from_instance('assign', $assign->id, $assign->courseid);
1256 $cm = context_module::instance($mod->id);
1257 $assignment = new assign($cm, null, null);
1258 $gradefeedbackenabled = $assignment->is_gradebook_feedback_enabled();
1261 if ($assign->grade > 0) {
1262 $params['gradetype'] = GRADE_TYPE_VALUE;
1263 $params['grademax'] = $assign->grade;
1264 $params['grademin'] = 0;
1266 } else if ($assign->grade < 0) {
1267 $params['gradetype'] = GRADE_TYPE_SCALE;
1268 $params['scaleid'] = -$assign->grade;
1270 } else if ($gradefeedbackenabled) {
1271 // $assign->grade == 0 and feedback enabled.
1272 $params['gradetype'] = GRADE_TYPE_TEXT;
1273 } else {
1274 // $assign->grade == 0 and no feedback enabled.
1275 $params['gradetype'] = GRADE_TYPE_NONE;
1278 if ($grades === 'reset') {
1279 $params['reset'] = true;
1280 $grades = null;
1283 return grade_update('mod/assign',
1284 $assign->courseid,
1285 'mod',
1286 'assign',
1287 $assign->id,
1289 $grades,
1290 $params);
1294 * Return grade for given user or all users.
1296 * @param stdClass $assign record of assign with an additional cmidnumber
1297 * @param int $userid optional user id, 0 means all users
1298 * @return array array of grades, false if none
1300 function assign_get_user_grades($assign, $userid=0) {
1301 global $CFG;
1303 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1305 $cm = get_coursemodule_from_instance('assign', $assign->id, 0, false, MUST_EXIST);
1306 $context = context_module::instance($cm->id);
1307 $assignment = new assign($context, null, null);
1308 $assignment->set_instance($assign);
1309 return $assignment->get_user_grades_for_gradebook($userid);
1313 * Update activity grades.
1315 * @param stdClass $assign database record
1316 * @param int $userid specific user only, 0 means all
1317 * @param bool $nullifnone - not used
1319 function assign_update_grades($assign, $userid=0, $nullifnone=true) {
1320 global $CFG;
1321 require_once($CFG->libdir.'/gradelib.php');
1323 if ($assign->grade == 0) {
1324 assign_grade_item_update($assign);
1326 } else if ($grades = assign_get_user_grades($assign, $userid)) {
1327 foreach ($grades as $k => $v) {
1328 if ($v->rawgrade == -1) {
1329 $grades[$k]->rawgrade = null;
1332 assign_grade_item_update($assign, $grades);
1334 } else {
1335 assign_grade_item_update($assign);
1340 * List the file areas that can be browsed.
1342 * @param stdClass $course
1343 * @param stdClass $cm
1344 * @param stdClass $context
1345 * @return array
1347 function assign_get_file_areas($course, $cm, $context) {
1348 global $CFG;
1349 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1351 $areas = array(ASSIGN_INTROATTACHMENT_FILEAREA => get_string('introattachments', 'mod_assign'));
1353 $assignment = new assign($context, $cm, $course);
1354 foreach ($assignment->get_submission_plugins() as $plugin) {
1355 if ($plugin->is_visible()) {
1356 $pluginareas = $plugin->get_file_areas();
1358 if ($pluginareas) {
1359 $areas = array_merge($areas, $pluginareas);
1363 foreach ($assignment->get_feedback_plugins() as $plugin) {
1364 if ($plugin->is_visible()) {
1365 $pluginareas = $plugin->get_file_areas();
1367 if ($pluginareas) {
1368 $areas = array_merge($areas, $pluginareas);
1373 return $areas;
1377 * File browsing support for assign module.
1379 * @param file_browser $browser
1380 * @param object $areas
1381 * @param object $course
1382 * @param object $cm
1383 * @param object $context
1384 * @param string $filearea
1385 * @param int $itemid
1386 * @param string $filepath
1387 * @param string $filename
1388 * @return object file_info instance or null if not found
1390 function assign_get_file_info($browser,
1391 $areas,
1392 $course,
1393 $cm,
1394 $context,
1395 $filearea,
1396 $itemid,
1397 $filepath,
1398 $filename) {
1399 global $CFG;
1400 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1402 if ($context->contextlevel != CONTEXT_MODULE) {
1403 return null;
1406 $urlbase = $CFG->wwwroot.'/pluginfile.php';
1407 $fs = get_file_storage();
1408 $filepath = is_null($filepath) ? '/' : $filepath;
1409 $filename = is_null($filename) ? '.' : $filename;
1411 // Need to find where this belongs to.
1412 $assignment = new assign($context, $cm, $course);
1413 if ($filearea === ASSIGN_INTROATTACHMENT_FILEAREA) {
1414 if (!has_capability('moodle/course:managefiles', $context)) {
1415 // Students can not peak here!
1416 return null;
1418 if (!($storedfile = $fs->get_file($assignment->get_context()->id,
1419 'mod_assign', $filearea, 0, $filepath, $filename))) {
1420 return null;
1422 return new file_info_stored($browser,
1423 $assignment->get_context(),
1424 $storedfile,
1425 $urlbase,
1426 $filearea,
1427 $itemid,
1428 true,
1429 true,
1430 false);
1433 $pluginowner = null;
1434 foreach ($assignment->get_submission_plugins() as $plugin) {
1435 if ($plugin->is_visible()) {
1436 $pluginareas = $plugin->get_file_areas();
1438 if (array_key_exists($filearea, $pluginareas)) {
1439 $pluginowner = $plugin;
1440 break;
1444 if (!$pluginowner) {
1445 foreach ($assignment->get_feedback_plugins() as $plugin) {
1446 if ($plugin->is_visible()) {
1447 $pluginareas = $plugin->get_file_areas();
1449 if (array_key_exists($filearea, $pluginareas)) {
1450 $pluginowner = $plugin;
1451 break;
1457 if (!$pluginowner) {
1458 return null;
1461 $result = $pluginowner->get_file_info($browser, $filearea, $itemid, $filepath, $filename);
1462 return $result;
1466 * Prints the complete info about a user's interaction with an assignment.
1468 * @param stdClass $course
1469 * @param stdClass $user
1470 * @param stdClass $coursemodule
1471 * @param stdClass $assign the database assign record
1473 * This prints the submission summary and feedback summary for this student.
1475 function assign_user_complete($course, $user, $coursemodule, $assign) {
1476 global $CFG;
1477 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1479 $context = context_module::instance($coursemodule->id);
1481 $assignment = new assign($context, $coursemodule, $course);
1483 echo $assignment->view_student_summary($user, false);
1487 * Rescale all grades for this activity and push the new grades to the gradebook.
1489 * @param stdClass $course Course db record
1490 * @param stdClass $cm Course module db record
1491 * @param float $oldmin
1492 * @param float $oldmax
1493 * @param float $newmin
1494 * @param float $newmax
1496 function assign_rescale_activity_grades($course, $cm, $oldmin, $oldmax, $newmin, $newmax) {
1497 global $DB;
1499 if ($oldmax <= $oldmin) {
1500 // Grades cannot be scaled.
1501 return false;
1503 $scale = ($newmax - $newmin) / ($oldmax - $oldmin);
1504 if (($newmax - $newmin) <= 1) {
1505 // We would lose too much precision, lets bail.
1506 return false;
1509 $params = array(
1510 'p1' => $oldmin,
1511 'p2' => $scale,
1512 'p3' => $newmin,
1513 'a' => $cm->instance
1516 $sql = 'UPDATE {assign_grades} set grade = (((grade - :p1) * :p2) + :p3) where assignment = :a';
1517 $dbupdate = $DB->execute($sql, $params);
1518 if (!$dbupdate) {
1519 return false;
1522 // Now re-push all grades to the gradebook.
1523 $dbparams = array('id' => $cm->instance);
1524 $assign = $DB->get_record('assign', $dbparams);
1525 $assign->cmidnumber = $cm->idnumber;
1527 assign_update_grades($assign);
1529 return true;
1533 * Print the grade information for the assignment for this user.
1535 * @param stdClass $course
1536 * @param stdClass $user
1537 * @param stdClass $coursemodule
1538 * @param stdClass $assignment
1540 function assign_user_outline($course, $user, $coursemodule, $assignment) {
1541 global $CFG;
1542 require_once($CFG->libdir.'/gradelib.php');
1543 require_once($CFG->dirroot.'/grade/grading/lib.php');
1545 $gradinginfo = grade_get_grades($course->id,
1546 'mod',
1547 'assign',
1548 $assignment->id,
1549 $user->id);
1551 $gradingitem = $gradinginfo->items[0];
1552 $gradebookgrade = $gradingitem->grades[$user->id];
1554 if (empty($gradebookgrade->str_long_grade)) {
1555 return null;
1557 $result = new stdClass();
1558 $result->info = get_string('outlinegrade', 'assign', $gradebookgrade->str_long_grade);
1559 $result->time = $gradebookgrade->dategraded;
1561 return $result;
1565 * Obtains the automatic completion state for this module based on any conditions
1566 * in assign settings.
1568 * @param object $course Course
1569 * @param object $cm Course-module
1570 * @param int $userid User ID
1571 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
1572 * @return bool True if completed, false if not, $type if conditions not set.
1574 function assign_get_completion_state($course, $cm, $userid, $type) {
1575 global $CFG, $DB;
1576 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1578 $assign = new assign(null, $cm, $course);
1580 // If completion option is enabled, evaluate it and return true/false.
1581 if ($assign->get_instance()->completionsubmit) {
1582 if ($assign->get_instance()->teamsubmission) {
1583 $submission = $assign->get_group_submission($userid, 0, false);
1584 } else {
1585 $submission = $assign->get_user_submission($userid, false);
1587 return $submission && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1588 } else {
1589 // Completion option is not enabled so just return $type.
1590 return $type;
1595 * Serves intro attachment files.
1597 * @param mixed $course course or id of the course
1598 * @param mixed $cm course module or id of the course module
1599 * @param context $context
1600 * @param string $filearea
1601 * @param array $args
1602 * @param bool $forcedownload
1603 * @param array $options additional options affecting the file serving
1604 * @return bool false if file not found, does not return if found - just send the file
1606 function assign_pluginfile($course,
1607 $cm,
1608 context $context,
1609 $filearea,
1610 $args,
1611 $forcedownload,
1612 array $options=array()) {
1613 global $CFG;
1615 if ($context->contextlevel != CONTEXT_MODULE) {
1616 return false;
1619 require_login($course, false, $cm);
1620 if (!has_capability('mod/assign:view', $context)) {
1621 return false;
1624 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1625 $assign = new assign($context, $cm, $course);
1627 if ($filearea !== ASSIGN_INTROATTACHMENT_FILEAREA) {
1628 return false;
1630 if (!$assign->show_intro()) {
1631 return false;
1634 $itemid = (int)array_shift($args);
1635 if ($itemid != 0) {
1636 return false;
1639 $relativepath = implode('/', $args);
1641 $fullpath = "/{$context->id}/mod_assign/$filearea/$itemid/$relativepath";
1643 $fs = get_file_storage();
1644 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1645 return false;
1647 send_stored_file($file, 0, 0, $forcedownload, $options);
1651 * Serve the grading panel as a fragment.
1653 * @param array $args List of named arguments for the fragment loader.
1654 * @return string
1656 function mod_assign_output_fragment_gradingpanel($args) {
1657 global $CFG;
1659 $context = $args['context'];
1661 if ($context->contextlevel != CONTEXT_MODULE) {
1662 return null;
1664 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1665 $assign = new assign($context, null, null);
1667 $userid = clean_param($args['userid'], PARAM_INT);
1668 $attemptnumber = clean_param($args['attemptnumber'], PARAM_INT);
1669 $formdata = array();
1670 if (!empty($args['jsonformdata'])) {
1671 $serialiseddata = json_decode($args['jsonformdata']);
1672 parse_str($serialiseddata, $formdata);
1674 $viewargs = array(
1675 'userid' => $userid,
1676 'attemptnumber' => $attemptnumber,
1677 'formdata' => $formdata
1680 return $assign->view('gradingpanel', $viewargs);
1684 * Check if the module has any update that affects the current user since a given time.
1686 * @param cm_info $cm course module data
1687 * @param int $from the time to check updates from
1688 * @param array $filter if we need to check only specific updates
1689 * @return stdClass an object with the different type of areas indicating if they were updated or not
1690 * @since Moodle 3.2
1692 function assign_check_updates_since(cm_info $cm, $from, $filter = array()) {
1693 global $DB, $USER, $CFG;
1694 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1696 $updates = new stdClass();
1697 $updates = course_check_module_updates_since($cm, $from, array(ASSIGN_INTROATTACHMENT_FILEAREA), $filter);
1699 // Check if there is a new submission by the user or new grades.
1700 $select = 'assignment = :id AND userid = :userid AND (timecreated > :since1 OR timemodified > :since2)';
1701 $params = array('id' => $cm->instance, 'userid' => $USER->id, 'since1' => $from, 'since2' => $from);
1702 $updates->submissions = (object) array('updated' => false);
1703 $submissions = $DB->get_records_select('assign_submission', $select, $params, '', 'id');
1704 if (!empty($submissions)) {
1705 $updates->submissions->updated = true;
1706 $updates->submissions->itemids = array_keys($submissions);
1709 $updates->grades = (object) array('updated' => false);
1710 $grades = $DB->get_records_select('assign_grades', $select, $params, '', 'id');
1711 if (!empty($grades)) {
1712 $updates->grades->updated = true;
1713 $updates->grades->itemids = array_keys($grades);
1716 return $updates;