MDL-57411 course: Return modules updates for teachers
[moodle.git] / mod / assign / lib.php
blobb6a180760528b53392b9aeb1769d82daf0ccaa36
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 * @param assign $assign the assign object.
208 * @param object $override (optional) limit to a specific override
210 function assign_update_events($assign, $override = null) {
211 global $CFG, $DB;
213 require_once($CFG->dirroot . '/calendar/lib.php');
215 $assigninstance = $assign->get_instance();
217 // Load the old events relating to this assign.
218 $conds = array('modulename' => 'assign', 'instance' => $assigninstance->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 to-do list of all that needs to be updated.
230 if (empty($override)) {
231 // We are updating the primary settings for the assign, so we need to add all the overrides.
232 $overrides = $DB->get_records('assign_overrides', array('assignid' => $assigninstance->id));
233 // As well as the original assign (empty override).
234 $overrides[] = new stdClass();
235 } else {
236 // Just do the one override.
237 $overrides = array($override);
240 if (!empty($assign->get_course_module())) {
241 $cmid = $assign->get_course_module()->id;
242 } else {
243 $cmid = get_coursemodule_from_instance('assign', $assigninstance->id, $assigninstance->course)->id;
246 foreach ($overrides as $current) {
247 $groupid = isset($current->groupid) ? $current->groupid : 0;
248 $userid = isset($current->userid) ? $current->userid : 0;
249 $duedate = isset($current->duedate) ? $current->duedate : $assigninstance->duedate;
251 // Only add 'due' events for an override if they differ from the assign default.
252 $addclose = empty($current->id) || !empty($current->duedate);
254 $event = new stdClass();
255 $event->description = format_module_intro('assign', $assigninstance, $cmid);
256 // Events module won't show user events when the courseid is nonzero.
257 $event->courseid = ($userid) ? 0 : $assigninstance->course;
258 $event->groupid = $groupid;
259 $event->userid = $userid;
260 $event->modulename = 'assign';
261 $event->instance = $assigninstance->id;
262 $event->timestart = $duedate;
263 $event->timeduration = 0;
264 $event->visible = instance_is_visible('assign', $assigninstance);
265 $event->eventtype = 'due';
267 // Determine the event name and priority.
268 if ($groupid) {
269 // Group override event.
270 $params = new stdClass();
271 $params->assign = $assigninstance->name;
272 $params->group = groups_get_group_name($groupid);
273 if ($params->group === false) {
274 // Group doesn't exist, just skip it.
275 continue;
277 $eventname = get_string('overridegroupeventname', 'assign', $params);
278 // Set group override priority.
279 if (isset($current->sortorder)) {
280 $event->priority = $current->sortorder;
282 } else if ($userid) {
283 // User override event.
284 $params = new stdClass();
285 $params->assign = $assigninstance->name;
286 $eventname = get_string('overrideusereventname', 'assign', $params);
287 // Set user override priority.
288 $event->priority = CALENDAR_EVENT_USER_OVERRIDE_PRIORITY;
289 } else {
290 // The parent event.
291 $eventname = $assigninstance->name;
294 if ($duedate && $addclose) {
295 if ($oldevent = array_shift($oldevents)) {
296 $event->id = $oldevent->id;
297 } else {
298 unset($event->id);
300 $event->name = $eventname.' ('.get_string('duedate', 'assign').')';
301 $event->timestart = $duedate;
302 $event->eventtype = 'due';
303 calendar_event::create($event);
307 // Delete any leftover events.
308 foreach ($oldevents as $badevent) {
309 $badevent = calendar_event::load($badevent);
310 $badevent->delete();
315 * Return the list if Moodle features this module supports
317 * @param string $feature FEATURE_xx constant for requested feature
318 * @return mixed True if module supports feature, null if doesn't know
320 function assign_supports($feature) {
321 switch($feature) {
322 case FEATURE_GROUPS:
323 return true;
324 case FEATURE_GROUPINGS:
325 return true;
326 case FEATURE_MOD_INTRO:
327 return true;
328 case FEATURE_COMPLETION_TRACKS_VIEWS:
329 return true;
330 case FEATURE_COMPLETION_HAS_RULES:
331 return true;
332 case FEATURE_GRADE_HAS_GRADE:
333 return true;
334 case FEATURE_GRADE_OUTCOMES:
335 return true;
336 case FEATURE_BACKUP_MOODLE2:
337 return true;
338 case FEATURE_SHOW_DESCRIPTION:
339 return true;
340 case FEATURE_ADVANCED_GRADING:
341 return true;
342 case FEATURE_PLAGIARISM:
343 return true;
344 case FEATURE_COMMENT:
345 return true;
347 default:
348 return null;
353 * Lists all gradable areas for the advanced grading methods gramework
355 * @return array('string'=>'string') An array with area names as keys and descriptions as values
357 function assign_grading_areas_list() {
358 return array('submissions'=>get_string('submissions', 'assign'));
363 * extend an assigment navigation settings
365 * @param settings_navigation $settings
366 * @param navigation_node $navref
367 * @return void
369 function assign_extend_settings_navigation(settings_navigation $settings, navigation_node $navref) {
370 global $PAGE, $DB;
372 // We want to add these new nodes after the Edit settings node, and before the
373 // Locally assigned roles node. Of course, both of those are controlled by capabilities.
374 $keys = $navref->get_children_key_list();
375 $beforekey = null;
376 $i = array_search('modedit', $keys);
377 if ($i === false and array_key_exists(0, $keys)) {
378 $beforekey = $keys[0];
379 } else if (array_key_exists($i + 1, $keys)) {
380 $beforekey = $keys[$i + 1];
383 $cm = $PAGE->cm;
384 if (!$cm) {
385 return;
388 $context = $cm->context;
389 $course = $PAGE->course;
391 if (!$course) {
392 return;
395 if (has_capability('mod/assign:manageoverrides', $PAGE->cm->context)) {
396 $url = new moodle_url('/mod/assign/overrides.php', array('cmid' => $PAGE->cm->id));
397 $node = navigation_node::create(get_string('groupoverrides', 'assign'),
398 new moodle_url($url, array('mode' => 'group')),
399 navigation_node::TYPE_SETTING, null, 'mod_assign_groupoverrides');
400 $navref->add_node($node, $beforekey);
402 $node = navigation_node::create(get_string('useroverrides', 'assign'),
403 new moodle_url($url, array('mode' => 'user')),
404 navigation_node::TYPE_SETTING, null, 'mod_assign_useroverrides');
405 $navref->add_node($node, $beforekey);
408 // Link to gradebook.
409 if (has_capability('gradereport/grader:view', $cm->context) &&
410 has_capability('moodle/grade:viewall', $cm->context)) {
411 $link = new moodle_url('/grade/report/grader/index.php', array('id' => $course->id));
412 $linkname = get_string('viewgradebook', 'assign');
413 $node = $navref->add($linkname, $link, navigation_node::TYPE_SETTING);
416 // Link to download all submissions.
417 if (has_any_capability(array('mod/assign:grade', 'mod/assign:viewgrades'), $context)) {
418 $link = new moodle_url('/mod/assign/view.php', array('id' => $cm->id, 'action'=>'grading'));
419 $node = $navref->add(get_string('viewgrading', 'assign'), $link, navigation_node::TYPE_SETTING);
421 $link = new moodle_url('/mod/assign/view.php', array('id' => $cm->id, 'action'=>'downloadall'));
422 $node = $navref->add(get_string('downloadall', 'assign'), $link, navigation_node::TYPE_SETTING);
425 if (has_capability('mod/assign:revealidentities', $context)) {
426 $dbparams = array('id'=>$cm->instance);
427 $assignment = $DB->get_record('assign', $dbparams, 'blindmarking, revealidentities');
429 if ($assignment && $assignment->blindmarking && !$assignment->revealidentities) {
430 $urlparams = array('id' => $cm->id, 'action'=>'revealidentities');
431 $url = new moodle_url('/mod/assign/view.php', $urlparams);
432 $linkname = get_string('revealidentities', 'assign');
433 $node = $navref->add($linkname, $url, navigation_node::TYPE_SETTING);
439 * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
440 * for the course (see resource).
442 * Given a course_module object, this function returns any "extra" information that may be needed
443 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
445 * @param stdClass $coursemodule The coursemodule object (record).
446 * @return cached_cm_info An object on information that the courses
447 * will know about (most noticeably, an icon).
449 function assign_get_coursemodule_info($coursemodule) {
450 global $CFG, $DB;
452 $dbparams = array('id'=>$coursemodule->instance);
453 $fields = 'id, name, alwaysshowdescription, allowsubmissionsfromdate, intro, introformat';
454 if (! $assignment = $DB->get_record('assign', $dbparams, $fields)) {
455 return false;
458 $result = new cached_cm_info();
459 $result->name = $assignment->name;
460 if ($coursemodule->showdescription) {
461 if ($assignment->alwaysshowdescription || time() > $assignment->allowsubmissionsfromdate) {
462 // Convert intro to html. Do not filter cached version, filters run at display time.
463 $result->content = format_module_intro('assign', $assignment, $coursemodule->id, false);
466 return $result;
470 * Return a list of page types
471 * @param string $pagetype current page type
472 * @param stdClass $parentcontext Block's parent context
473 * @param stdClass $currentcontext Current context of block
475 function assign_page_type_list($pagetype, $parentcontext, $currentcontext) {
476 $modulepagetype = array(
477 'mod-assign-*' => get_string('page-mod-assign-x', 'assign'),
478 'mod-assign-view' => get_string('page-mod-assign-view', 'assign'),
480 return $modulepagetype;
484 * Print an overview of all assignments
485 * for the courses.
487 * @param mixed $courses The list of courses to print the overview for
488 * @param array $htmlarray The array of html to return
490 * @return true
492 function assign_print_overview($courses, &$htmlarray) {
493 global $CFG, $DB;
495 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
496 return true;
499 if (!$assignments = get_all_instances_in_courses('assign', $courses)) {
500 return true;
503 $assignmentids = array();
505 // Do assignment_base::isopen() here without loading the whole thing for speed.
506 foreach ($assignments as $key => $assignment) {
507 $time = time();
508 $isopen = false;
509 if ($assignment->duedate) {
510 $duedate = false;
511 if ($assignment->cutoffdate) {
512 $duedate = $assignment->cutoffdate;
514 if ($duedate) {
515 $isopen = ($assignment->allowsubmissionsfromdate <= $time && $time <= $duedate);
516 } else {
517 $isopen = ($assignment->allowsubmissionsfromdate <= $time);
520 if ($isopen) {
521 $assignmentids[] = $assignment->id;
525 if (empty($assignmentids)) {
526 // No assignments to look at - we're done.
527 return true;
530 // Definitely something to print, now include the constants we need.
531 require_once($CFG->dirroot . '/mod/assign/locallib.php');
533 $strduedate = get_string('duedate', 'assign');
534 $strcutoffdate = get_string('nosubmissionsacceptedafter', 'assign');
535 $strnolatesubmissions = get_string('nolatesubmissions', 'assign');
536 $strduedateno = get_string('duedateno', 'assign');
537 $strassignment = get_string('modulename', 'assign');
539 // We do all possible database work here *outside* of the loop to ensure this scales.
540 list($sqlassignmentids, $assignmentidparams) = $DB->get_in_or_equal($assignmentids);
542 $mysubmissions = null;
543 $unmarkedsubmissions = null;
545 foreach ($assignments as $assignment) {
547 // Do not show assignments that are not open.
548 if (!in_array($assignment->id, $assignmentids)) {
549 continue;
552 $context = context_module::instance($assignment->coursemodule);
554 // Does the submission status of the assignment require notification?
555 if (has_capability('mod/assign:submit', $context, null, false)) {
556 // Does the submission status of the assignment require notification?
557 $submitdetails = assign_get_mysubmission_details_for_print_overview($mysubmissions, $sqlassignmentids,
558 $assignmentidparams, $assignment);
559 } else {
560 $submitdetails = false;
563 if (has_capability('mod/assign:grade', $context, null, false)) {
564 // Does the grading status of the assignment require notification ?
565 $gradedetails = assign_get_grade_details_for_print_overview($unmarkedsubmissions, $sqlassignmentids,
566 $assignmentidparams, $assignment, $context);
567 } else {
568 $gradedetails = false;
571 if (empty($submitdetails) && empty($gradedetails)) {
572 // There is no need to display this assignment as there is nothing to notify.
573 continue;
576 $dimmedclass = '';
577 if (!$assignment->visible) {
578 $dimmedclass = ' class="dimmed"';
580 $href = $CFG->wwwroot . '/mod/assign/view.php?id=' . $assignment->coursemodule;
581 $basestr = '<div class="assign overview">' .
582 '<div class="name">' .
583 $strassignment . ': '.
584 '<a ' . $dimmedclass .
585 'title="' . $strassignment . '" ' .
586 'href="' . $href . '">' .
587 format_string($assignment->name) .
588 '</a></div>';
589 if ($assignment->duedate) {
590 $userdate = userdate($assignment->duedate);
591 $basestr .= '<div class="info">' . $strduedate . ': ' . $userdate . '</div>';
592 } else {
593 $basestr .= '<div class="info">' . $strduedateno . '</div>';
595 if ($assignment->cutoffdate) {
596 if ($assignment->cutoffdate == $assignment->duedate) {
597 $basestr .= '<div class="info">' . $strnolatesubmissions . '</div>';
598 } else {
599 $userdate = userdate($assignment->cutoffdate);
600 $basestr .= '<div class="info">' . $strcutoffdate . ': ' . $userdate . '</div>';
604 // Show only relevant information.
605 if (!empty($submitdetails)) {
606 $basestr .= $submitdetails;
609 if (!empty($gradedetails)) {
610 $basestr .= $gradedetails;
612 $basestr .= '</div>';
614 if (empty($htmlarray[$assignment->course]['assign'])) {
615 $htmlarray[$assignment->course]['assign'] = $basestr;
616 } else {
617 $htmlarray[$assignment->course]['assign'] .= $basestr;
620 return true;
624 * This api generates html to be displayed to students in print overview section, related to their submission status of the given
625 * assignment.
627 * @param array $mysubmissions list of submissions of current user indexed by assignment id.
628 * @param string $sqlassignmentids sql clause used to filter open assignments.
629 * @param array $assignmentidparams sql params used to filter open assignments.
630 * @param stdClass $assignment current assignment
632 * @return bool|string html to display , false if nothing needs to be displayed.
633 * @throws coding_exception
635 function assign_get_mysubmission_details_for_print_overview(&$mysubmissions, $sqlassignmentids, $assignmentidparams,
636 $assignment) {
637 global $USER, $DB;
639 if ($assignment->nosubmissions) {
640 // Offline assignment. No need to display alerts for offline assignments.
641 return false;
644 $strnotsubmittedyet = get_string('notsubmittedyet', 'assign');
646 if (!isset($mysubmissions)) {
648 // Get all user submissions, indexed by assignment id.
649 $dbparams = array_merge(array($USER->id), $assignmentidparams, array($USER->id));
650 $mysubmissions = $DB->get_records_sql('SELECT a.id AS assignment,
651 a.nosubmissions AS nosubmissions,
652 g.timemodified AS timemarked,
653 g.grader AS grader,
654 g.grade AS grade,
655 s.status AS status
656 FROM {assign} a, {assign_submission} s
657 LEFT JOIN {assign_grades} g ON
658 g.assignment = s.assignment AND
659 g.userid = ? AND
660 g.attemptnumber = s.attemptnumber
661 WHERE a.id ' . $sqlassignmentids . ' AND
662 s.latest = 1 AND
663 s.assignment = a.id AND
664 s.userid = ?', $dbparams);
667 $submitdetails = '';
668 $submitdetails .= '<div class="details">';
669 $submitdetails .= get_string('mysubmission', 'assign');
670 $submission = false;
672 if (isset($mysubmissions[$assignment->id])) {
673 $submission = $mysubmissions[$assignment->id];
676 if ($submission && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
677 // A valid submission already exists, no need to notify students about this.
678 return false;
681 // We need to show details only if a valid submission doesn't exist.
682 if (!$submission ||
683 !$submission->status ||
684 $submission->status == ASSIGN_SUBMISSION_STATUS_DRAFT ||
685 $submission->status == ASSIGN_SUBMISSION_STATUS_NEW
687 $submitdetails .= $strnotsubmittedyet;
688 } else {
689 $submitdetails .= get_string('submissionstatus_' . $submission->status, 'assign');
691 if ($assignment->markingworkflow) {
692 $workflowstate = $DB->get_field('assign_user_flags', 'workflowstate', array('assignment' =>
693 $assignment->id, 'userid' => $USER->id));
694 if ($workflowstate) {
695 $gradingstatus = 'markingworkflowstate' . $workflowstate;
696 } else {
697 $gradingstatus = 'markingworkflowstate' . ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED;
699 } else if (!empty($submission->grade) && $submission->grade !== null && $submission->grade >= 0) {
700 $gradingstatus = ASSIGN_GRADING_STATUS_GRADED;
701 } else {
702 $gradingstatus = ASSIGN_GRADING_STATUS_NOT_GRADED;
704 $submitdetails .= ', ' . get_string($gradingstatus, 'assign');
705 $submitdetails .= '</div>';
706 return $submitdetails;
710 * This api generates html to be displayed to teachers in print overview section, related to the grading status of the given
711 * assignment's submissions.
713 * @param array $unmarkedsubmissions list of submissions of that are currently unmarked indexed by assignment id.
714 * @param string $sqlassignmentids sql clause used to filter open assignments.
715 * @param array $assignmentidparams sql params used to filter open assignments.
716 * @param stdClass $assignment current assignment
717 * @param context $context context of the assignment.
719 * @return bool|string html to display , false if nothing needs to be displayed.
720 * @throws coding_exception
722 function assign_get_grade_details_for_print_overview(&$unmarkedsubmissions, $sqlassignmentids, $assignmentidparams,
723 $assignment, $context) {
724 global $DB;
725 if (!isset($unmarkedsubmissions)) {
726 // Build up and array of unmarked submissions indexed by assignment id/ userid
727 // for use where the user has grading rights on assignment.
728 $dbparams = array_merge(array(ASSIGN_SUBMISSION_STATUS_SUBMITTED), $assignmentidparams);
729 $rs = $DB->get_recordset_sql('SELECT s.assignment as assignment,
730 s.userid as userid,
731 s.id as id,
732 s.status as status,
733 g.timemodified as timegraded
734 FROM {assign_submission} s
735 LEFT JOIN {assign_grades} g ON
736 s.userid = g.userid AND
737 s.assignment = g.assignment AND
738 g.attemptnumber = s.attemptnumber
739 WHERE
740 ( g.timemodified is NULL OR
741 s.timemodified >= g.timemodified OR
742 g.grade IS NULL ) AND
743 s.timemodified IS NOT NULL AND
744 s.status = ? AND
745 s.latest = 1 AND
746 s.assignment ' . $sqlassignmentids, $dbparams);
748 $unmarkedsubmissions = array();
749 foreach ($rs as $rd) {
750 $unmarkedsubmissions[$rd->assignment][$rd->userid] = $rd->id;
752 $rs->close();
755 // Count how many people can submit.
756 $submissions = 0;
757 if ($students = get_enrolled_users($context, 'mod/assign:view', 0, 'u.id')) {
758 foreach ($students as $student) {
759 if (isset($unmarkedsubmissions[$assignment->id][$student->id])) {
760 $submissions++;
765 if ($submissions) {
766 $urlparams = array('id' => $assignment->coursemodule, 'action' => 'grading');
767 $url = new moodle_url('/mod/assign/view.php', $urlparams);
768 $gradedetails = '<div class="details">' .
769 '<a href="' . $url . '">' .
770 get_string('submissionsnotgraded', 'assign', $submissions) .
771 '</a></div>';
772 return $gradedetails;
773 } else {
774 return false;
780 * Print recent activity from all assignments in a given course
782 * This is used by the recent activity block
783 * @param mixed $course the course to print activity for
784 * @param bool $viewfullnames boolean to determine whether to show full names or not
785 * @param int $timestart the time the rendering started
786 * @return bool true if activity was printed, false otherwise.
788 function assign_print_recent_activity($course, $viewfullnames, $timestart) {
789 global $CFG, $USER, $DB, $OUTPUT;
790 require_once($CFG->dirroot . '/mod/assign/locallib.php');
792 // Do not use log table if possible, it may be huge.
794 $dbparams = array($timestart, $course->id, 'assign', ASSIGN_SUBMISSION_STATUS_SUBMITTED);
795 $namefields = user_picture::fields('u', null, 'userid');
796 if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, um.id as recordid,
797 $namefields
798 FROM {assign_submission} asb
799 JOIN {assign} a ON a.id = asb.assignment
800 JOIN {course_modules} cm ON cm.instance = a.id
801 JOIN {modules} md ON md.id = cm.module
802 JOIN {user} u ON u.id = asb.userid
803 LEFT JOIN {assign_user_mapping} um ON um.userid = u.id AND um.assignment = a.id
804 WHERE asb.timemodified > ? AND
805 asb.latest = 1 AND
806 a.course = ? AND
807 md.name = ? AND
808 asb.status = ?
809 ORDER BY asb.timemodified ASC", $dbparams)) {
810 return false;
813 $modinfo = get_fast_modinfo($course);
814 $show = array();
815 $grader = array();
817 $showrecentsubmissions = get_config('assign', 'showrecentsubmissions');
819 foreach ($submissions as $submission) {
820 if (!array_key_exists($submission->cmid, $modinfo->get_cms())) {
821 continue;
823 $cm = $modinfo->get_cm($submission->cmid);
824 if (!$cm->uservisible) {
825 continue;
827 if ($submission->userid == $USER->id) {
828 $show[] = $submission;
829 continue;
832 $context = context_module::instance($submission->cmid);
833 // The act of submitting of assignment may be considered private -
834 // only graders will see it if specified.
835 if (empty($showrecentsubmissions)) {
836 if (!array_key_exists($cm->id, $grader)) {
837 $grader[$cm->id] = has_capability('moodle/grade:viewall', $context);
839 if (!$grader[$cm->id]) {
840 continue;
844 $groupmode = groups_get_activity_groupmode($cm, $course);
846 if ($groupmode == SEPARATEGROUPS &&
847 !has_capability('moodle/site:accessallgroups', $context)) {
848 if (isguestuser()) {
849 // Shortcut - guest user does not belong into any group.
850 continue;
853 // This will be slow - show only users that share group with me in this cm.
854 if (!$modinfo->get_groups($cm->groupingid)) {
855 continue;
857 $usersgroups = groups_get_all_groups($course->id, $submission->userid, $cm->groupingid);
858 if (is_array($usersgroups)) {
859 $usersgroups = array_keys($usersgroups);
860 $intersect = array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid));
861 if (empty($intersect)) {
862 continue;
866 $show[] = $submission;
869 if (empty($show)) {
870 return false;
873 echo $OUTPUT->heading(get_string('newsubmissions', 'assign').':', 3);
875 foreach ($show as $submission) {
876 $cm = $modinfo->get_cm($submission->cmid);
877 $context = context_module::instance($submission->cmid);
878 $assign = new assign($context, $cm, $cm->course);
879 $link = $CFG->wwwroot.'/mod/assign/view.php?id='.$cm->id;
880 // Obscure first and last name if blind marking enabled.
881 if ($assign->is_blind_marking()) {
882 $submission->firstname = get_string('participant', 'mod_assign');
883 if (empty($submission->recordid)) {
884 $submission->recordid = $assign->get_uniqueid_for_user($submission->userid);
886 $submission->lastname = $submission->recordid;
888 print_recent_activity_note($submission->timemodified,
889 $submission,
890 $cm->name,
891 $link,
892 false,
893 $viewfullnames);
896 return true;
900 * Returns all assignments since a given time.
902 * @param array $activities The activity information is returned in this array
903 * @param int $index The current index in the activities array
904 * @param int $timestart The earliest activity to show
905 * @param int $courseid Limit the search to this course
906 * @param int $cmid The course module id
907 * @param int $userid Optional user id
908 * @param int $groupid Optional group id
909 * @return void
911 function assign_get_recent_mod_activity(&$activities,
912 &$index,
913 $timestart,
914 $courseid,
915 $cmid,
916 $userid=0,
917 $groupid=0) {
918 global $CFG, $COURSE, $USER, $DB;
920 require_once($CFG->dirroot . '/mod/assign/locallib.php');
922 if ($COURSE->id == $courseid) {
923 $course = $COURSE;
924 } else {
925 $course = $DB->get_record('course', array('id'=>$courseid));
928 $modinfo = get_fast_modinfo($course);
930 $cm = $modinfo->get_cm($cmid);
931 $params = array();
932 if ($userid) {
933 $userselect = 'AND u.id = :userid';
934 $params['userid'] = $userid;
935 } else {
936 $userselect = '';
939 if ($groupid) {
940 $groupselect = 'AND gm.groupid = :groupid';
941 $groupjoin = 'JOIN {groups_members} gm ON gm.userid=u.id';
942 $params['groupid'] = $groupid;
943 } else {
944 $groupselect = '';
945 $groupjoin = '';
948 $params['cminstance'] = $cm->instance;
949 $params['timestart'] = $timestart;
950 $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
952 $userfields = user_picture::fields('u', null, 'userid');
954 if (!$submissions = $DB->get_records_sql('SELECT asb.id, asb.timemodified, ' .
955 $userfields .
956 ' FROM {assign_submission} asb
957 JOIN {assign} a ON a.id = asb.assignment
958 JOIN {user} u ON u.id = asb.userid ' .
959 $groupjoin .
960 ' WHERE asb.timemodified > :timestart AND
961 asb.status = :submitted AND
962 a.id = :cminstance
963 ' . $userselect . ' ' . $groupselect .
964 ' ORDER BY asb.timemodified ASC', $params)) {
965 return;
968 $groupmode = groups_get_activity_groupmode($cm, $course);
969 $cmcontext = context_module::instance($cm->id);
970 $grader = has_capability('moodle/grade:viewall', $cmcontext);
971 $accessallgroups = has_capability('moodle/site:accessallgroups', $cmcontext);
972 $viewfullnames = has_capability('moodle/site:viewfullnames', $cmcontext);
975 $showrecentsubmissions = get_config('assign', 'showrecentsubmissions');
976 $show = array();
977 foreach ($submissions as $submission) {
978 if ($submission->userid == $USER->id) {
979 $show[] = $submission;
980 continue;
982 // The act of submitting of assignment may be considered private -
983 // only graders will see it if specified.
984 if (empty($showrecentsubmissions)) {
985 if (!$grader) {
986 continue;
990 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
991 if (isguestuser()) {
992 // Shortcut - guest user does not belong into any group.
993 continue;
996 // This will be slow - show only users that share group with me in this cm.
997 if (!$modinfo->get_groups($cm->groupingid)) {
998 continue;
1000 $usersgroups = groups_get_all_groups($course->id, $submission->userid, $cm->groupingid);
1001 if (is_array($usersgroups)) {
1002 $usersgroups = array_keys($usersgroups);
1003 $intersect = array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid));
1004 if (empty($intersect)) {
1005 continue;
1009 $show[] = $submission;
1012 if (empty($show)) {
1013 return;
1016 if ($grader) {
1017 require_once($CFG->libdir.'/gradelib.php');
1018 $userids = array();
1019 foreach ($show as $id => $submission) {
1020 $userids[] = $submission->userid;
1022 $grades = grade_get_grades($courseid, 'mod', 'assign', $cm->instance, $userids);
1025 $aname = format_string($cm->name, true);
1026 foreach ($show as $submission) {
1027 $activity = new stdClass();
1029 $activity->type = 'assign';
1030 $activity->cmid = $cm->id;
1031 $activity->name = $aname;
1032 $activity->sectionnum = $cm->sectionnum;
1033 $activity->timestamp = $submission->timemodified;
1034 $activity->user = new stdClass();
1035 if ($grader) {
1036 $activity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
1039 $userfields = explode(',', user_picture::fields());
1040 foreach ($userfields as $userfield) {
1041 if ($userfield == 'id') {
1042 // Aliased in SQL above.
1043 $activity->user->{$userfield} = $submission->userid;
1044 } else {
1045 $activity->user->{$userfield} = $submission->{$userfield};
1048 $activity->user->fullname = fullname($submission, $viewfullnames);
1050 $activities[$index++] = $activity;
1053 return;
1057 * Print recent activity from all assignments in a given course
1059 * This is used by course/recent.php
1060 * @param stdClass $activity
1061 * @param int $courseid
1062 * @param bool $detail
1063 * @param array $modnames
1065 function assign_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
1066 global $CFG, $OUTPUT;
1068 echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
1070 echo '<tr><td class="userpicture" valign="top">';
1071 echo $OUTPUT->user_picture($activity->user);
1072 echo '</td><td>';
1074 if ($detail) {
1075 $modname = $modnames[$activity->type];
1076 echo '<div class="title">';
1077 echo $OUTPUT->image_icon('icon', $modname, 'assign');
1078 echo '<a href="' . $CFG->wwwroot . '/mod/assign/view.php?id=' . $activity->cmid . '">';
1079 echo $activity->name;
1080 echo '</a>';
1081 echo '</div>';
1084 if (isset($activity->grade)) {
1085 echo '<div class="grade">';
1086 echo get_string('grade').': ';
1087 echo $activity->grade;
1088 echo '</div>';
1091 echo '<div class="user">';
1092 echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->id}&amp;course=$courseid\">";
1093 echo "{$activity->user->fullname}</a> - " . userdate($activity->timestamp);
1094 echo '</div>';
1096 echo '</td></tr></table>';
1100 * Checks if a scale is being used by an assignment.
1102 * This is used by the backup code to decide whether to back up a scale
1103 * @param int $assignmentid
1104 * @param int $scaleid
1105 * @return boolean True if the scale is used by the assignment
1107 function assign_scale_used($assignmentid, $scaleid) {
1108 global $DB;
1110 $return = false;
1111 $rec = $DB->get_record('assign', array('id'=>$assignmentid, 'grade'=>-$scaleid));
1113 if (!empty($rec) && !empty($scaleid)) {
1114 $return = true;
1117 return $return;
1121 * Checks if scale is being used by any instance of assignment
1123 * This is used to find out if scale used anywhere
1124 * @param int $scaleid
1125 * @return boolean True if the scale is used by any assignment
1127 function assign_scale_used_anywhere($scaleid) {
1128 global $DB;
1130 if ($scaleid and $DB->record_exists('assign', array('grade'=>-$scaleid))) {
1131 return true;
1132 } else {
1133 return false;
1138 * List the actions that correspond to a view of this module.
1139 * This is used by the participation report.
1141 * Note: This is not used by new logging system. Event with
1142 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
1143 * be considered as view action.
1145 * @return array
1147 function assign_get_view_actions() {
1148 return array('view submission', 'view feedback');
1152 * List the actions that correspond to a post of this module.
1153 * This is used by the participation report.
1155 * Note: This is not used by new logging system. Event with
1156 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
1157 * will be considered as post action.
1159 * @return array
1161 function assign_get_post_actions() {
1162 return array('upload', 'submit', 'submit for grading');
1166 * Call cron on the assign module.
1168 function assign_cron() {
1169 global $CFG;
1171 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1172 assign::cron();
1174 $plugins = core_component::get_plugin_list('assignsubmission');
1176 foreach ($plugins as $name => $plugin) {
1177 $disabled = get_config('assignsubmission_' . $name, 'disabled');
1178 if (!$disabled) {
1179 $class = 'assign_submission_' . $name;
1180 require_once($CFG->dirroot . '/mod/assign/submission/' . $name . '/locallib.php');
1181 $class::cron();
1184 $plugins = core_component::get_plugin_list('assignfeedback');
1186 foreach ($plugins as $name => $plugin) {
1187 $disabled = get_config('assignfeedback_' . $name, 'disabled');
1188 if (!$disabled) {
1189 $class = 'assign_feedback_' . $name;
1190 require_once($CFG->dirroot . '/mod/assign/feedback/' . $name . '/locallib.php');
1191 $class::cron();
1195 return true;
1199 * Returns all other capabilities used by this module.
1200 * @return array Array of capability strings
1202 function assign_get_extra_capabilities() {
1203 return array('gradereport/grader:view',
1204 'moodle/grade:viewall',
1205 'moodle/site:viewfullnames',
1206 'moodle/site:config');
1210 * Create grade item for given assignment.
1212 * @param stdClass $assign record with extra cmidnumber
1213 * @param array $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
1214 * @return int 0 if ok, error code otherwise
1216 function assign_grade_item_update($assign, $grades=null) {
1217 global $CFG;
1218 require_once($CFG->libdir.'/gradelib.php');
1220 if (!isset($assign->courseid)) {
1221 $assign->courseid = $assign->course;
1224 $params = array('itemname'=>$assign->name, 'idnumber'=>$assign->cmidnumber);
1226 // Check if feedback plugin for gradebook is enabled, if yes then
1227 // gradetype = GRADE_TYPE_TEXT else GRADE_TYPE_NONE.
1228 $gradefeedbackenabled = false;
1230 if (isset($assign->gradefeedbackenabled)) {
1231 $gradefeedbackenabled = $assign->gradefeedbackenabled;
1232 } else if ($assign->grade == 0) { // Grade feedback is needed only when grade == 0.
1233 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1234 $mod = get_coursemodule_from_instance('assign', $assign->id, $assign->courseid);
1235 $cm = context_module::instance($mod->id);
1236 $assignment = new assign($cm, null, null);
1237 $gradefeedbackenabled = $assignment->is_gradebook_feedback_enabled();
1240 if ($assign->grade > 0) {
1241 $params['gradetype'] = GRADE_TYPE_VALUE;
1242 $params['grademax'] = $assign->grade;
1243 $params['grademin'] = 0;
1245 } else if ($assign->grade < 0) {
1246 $params['gradetype'] = GRADE_TYPE_SCALE;
1247 $params['scaleid'] = -$assign->grade;
1249 } else if ($gradefeedbackenabled) {
1250 // $assign->grade == 0 and feedback enabled.
1251 $params['gradetype'] = GRADE_TYPE_TEXT;
1252 } else {
1253 // $assign->grade == 0 and no feedback enabled.
1254 $params['gradetype'] = GRADE_TYPE_NONE;
1257 if ($grades === 'reset') {
1258 $params['reset'] = true;
1259 $grades = null;
1262 return grade_update('mod/assign',
1263 $assign->courseid,
1264 'mod',
1265 'assign',
1266 $assign->id,
1268 $grades,
1269 $params);
1273 * Return grade for given user or all users.
1275 * @param stdClass $assign record of assign with an additional cmidnumber
1276 * @param int $userid optional user id, 0 means all users
1277 * @return array array of grades, false if none
1279 function assign_get_user_grades($assign, $userid=0) {
1280 global $CFG;
1282 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1284 $cm = get_coursemodule_from_instance('assign', $assign->id, 0, false, MUST_EXIST);
1285 $context = context_module::instance($cm->id);
1286 $assignment = new assign($context, null, null);
1287 $assignment->set_instance($assign);
1288 return $assignment->get_user_grades_for_gradebook($userid);
1292 * Update activity grades.
1294 * @param stdClass $assign database record
1295 * @param int $userid specific user only, 0 means all
1296 * @param bool $nullifnone - not used
1298 function assign_update_grades($assign, $userid=0, $nullifnone=true) {
1299 global $CFG;
1300 require_once($CFG->libdir.'/gradelib.php');
1302 if ($assign->grade == 0) {
1303 assign_grade_item_update($assign);
1305 } else if ($grades = assign_get_user_grades($assign, $userid)) {
1306 foreach ($grades as $k => $v) {
1307 if ($v->rawgrade == -1) {
1308 $grades[$k]->rawgrade = null;
1311 assign_grade_item_update($assign, $grades);
1313 } else {
1314 assign_grade_item_update($assign);
1319 * List the file areas that can be browsed.
1321 * @param stdClass $course
1322 * @param stdClass $cm
1323 * @param stdClass $context
1324 * @return array
1326 function assign_get_file_areas($course, $cm, $context) {
1327 global $CFG;
1328 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1330 $areas = array(ASSIGN_INTROATTACHMENT_FILEAREA => get_string('introattachments', 'mod_assign'));
1332 $assignment = new assign($context, $cm, $course);
1333 foreach ($assignment->get_submission_plugins() as $plugin) {
1334 if ($plugin->is_visible()) {
1335 $pluginareas = $plugin->get_file_areas();
1337 if ($pluginareas) {
1338 $areas = array_merge($areas, $pluginareas);
1342 foreach ($assignment->get_feedback_plugins() as $plugin) {
1343 if ($plugin->is_visible()) {
1344 $pluginareas = $plugin->get_file_areas();
1346 if ($pluginareas) {
1347 $areas = array_merge($areas, $pluginareas);
1352 return $areas;
1356 * File browsing support for assign module.
1358 * @param file_browser $browser
1359 * @param object $areas
1360 * @param object $course
1361 * @param object $cm
1362 * @param object $context
1363 * @param string $filearea
1364 * @param int $itemid
1365 * @param string $filepath
1366 * @param string $filename
1367 * @return object file_info instance or null if not found
1369 function assign_get_file_info($browser,
1370 $areas,
1371 $course,
1372 $cm,
1373 $context,
1374 $filearea,
1375 $itemid,
1376 $filepath,
1377 $filename) {
1378 global $CFG;
1379 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1381 if ($context->contextlevel != CONTEXT_MODULE) {
1382 return null;
1385 $urlbase = $CFG->wwwroot.'/pluginfile.php';
1386 $fs = get_file_storage();
1387 $filepath = is_null($filepath) ? '/' : $filepath;
1388 $filename = is_null($filename) ? '.' : $filename;
1390 // Need to find where this belongs to.
1391 $assignment = new assign($context, $cm, $course);
1392 if ($filearea === ASSIGN_INTROATTACHMENT_FILEAREA) {
1393 if (!has_capability('moodle/course:managefiles', $context)) {
1394 // Students can not peak here!
1395 return null;
1397 if (!($storedfile = $fs->get_file($assignment->get_context()->id,
1398 'mod_assign', $filearea, 0, $filepath, $filename))) {
1399 return null;
1401 return new file_info_stored($browser,
1402 $assignment->get_context(),
1403 $storedfile,
1404 $urlbase,
1405 $filearea,
1406 $itemid,
1407 true,
1408 true,
1409 false);
1412 $pluginowner = null;
1413 foreach ($assignment->get_submission_plugins() as $plugin) {
1414 if ($plugin->is_visible()) {
1415 $pluginareas = $plugin->get_file_areas();
1417 if (array_key_exists($filearea, $pluginareas)) {
1418 $pluginowner = $plugin;
1419 break;
1423 if (!$pluginowner) {
1424 foreach ($assignment->get_feedback_plugins() as $plugin) {
1425 if ($plugin->is_visible()) {
1426 $pluginareas = $plugin->get_file_areas();
1428 if (array_key_exists($filearea, $pluginareas)) {
1429 $pluginowner = $plugin;
1430 break;
1436 if (!$pluginowner) {
1437 return null;
1440 $result = $pluginowner->get_file_info($browser, $filearea, $itemid, $filepath, $filename);
1441 return $result;
1445 * Prints the complete info about a user's interaction with an assignment.
1447 * @param stdClass $course
1448 * @param stdClass $user
1449 * @param stdClass $coursemodule
1450 * @param stdClass $assign the database assign record
1452 * This prints the submission summary and feedback summary for this student.
1454 function assign_user_complete($course, $user, $coursemodule, $assign) {
1455 global $CFG;
1456 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1458 $context = context_module::instance($coursemodule->id);
1460 $assignment = new assign($context, $coursemodule, $course);
1462 echo $assignment->view_student_summary($user, false);
1466 * Rescale all grades for this activity and push the new grades to the gradebook.
1468 * @param stdClass $course Course db record
1469 * @param stdClass $cm Course module db record
1470 * @param float $oldmin
1471 * @param float $oldmax
1472 * @param float $newmin
1473 * @param float $newmax
1475 function assign_rescale_activity_grades($course, $cm, $oldmin, $oldmax, $newmin, $newmax) {
1476 global $DB;
1478 if ($oldmax <= $oldmin) {
1479 // Grades cannot be scaled.
1480 return false;
1482 $scale = ($newmax - $newmin) / ($oldmax - $oldmin);
1483 if (($newmax - $newmin) <= 1) {
1484 // We would lose too much precision, lets bail.
1485 return false;
1488 $params = array(
1489 'p1' => $oldmin,
1490 'p2' => $scale,
1491 'p3' => $newmin,
1492 'a' => $cm->instance
1495 $sql = 'UPDATE {assign_grades} set grade = (((grade - :p1) * :p2) + :p3) where assignment = :a';
1496 $dbupdate = $DB->execute($sql, $params);
1497 if (!$dbupdate) {
1498 return false;
1501 // Now re-push all grades to the gradebook.
1502 $dbparams = array('id' => $cm->instance);
1503 $assign = $DB->get_record('assign', $dbparams);
1504 $assign->cmidnumber = $cm->idnumber;
1506 assign_update_grades($assign);
1508 return true;
1512 * Print the grade information for the assignment for this user.
1514 * @param stdClass $course
1515 * @param stdClass $user
1516 * @param stdClass $coursemodule
1517 * @param stdClass $assignment
1519 function assign_user_outline($course, $user, $coursemodule, $assignment) {
1520 global $CFG;
1521 require_once($CFG->libdir.'/gradelib.php');
1522 require_once($CFG->dirroot.'/grade/grading/lib.php');
1524 $gradinginfo = grade_get_grades($course->id,
1525 'mod',
1526 'assign',
1527 $assignment->id,
1528 $user->id);
1530 $gradingitem = $gradinginfo->items[0];
1531 $gradebookgrade = $gradingitem->grades[$user->id];
1533 if (empty($gradebookgrade->str_long_grade)) {
1534 return null;
1536 $result = new stdClass();
1537 $result->info = get_string('outlinegrade', 'assign', $gradebookgrade->str_long_grade);
1538 $result->time = $gradebookgrade->dategraded;
1540 return $result;
1544 * Obtains the automatic completion state for this module based on any conditions
1545 * in assign settings.
1547 * @param object $course Course
1548 * @param object $cm Course-module
1549 * @param int $userid User ID
1550 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
1551 * @return bool True if completed, false if not, $type if conditions not set.
1553 function assign_get_completion_state($course, $cm, $userid, $type) {
1554 global $CFG, $DB;
1555 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1557 $assign = new assign(null, $cm, $course);
1559 // If completion option is enabled, evaluate it and return true/false.
1560 if ($assign->get_instance()->completionsubmit) {
1561 if ($assign->get_instance()->teamsubmission) {
1562 $submission = $assign->get_group_submission($userid, 0, false);
1563 } else {
1564 $submission = $assign->get_user_submission($userid, false);
1566 return $submission && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1567 } else {
1568 // Completion option is not enabled so just return $type.
1569 return $type;
1574 * Serves intro attachment files.
1576 * @param mixed $course course or id of the course
1577 * @param mixed $cm course module or id of the course module
1578 * @param context $context
1579 * @param string $filearea
1580 * @param array $args
1581 * @param bool $forcedownload
1582 * @param array $options additional options affecting the file serving
1583 * @return bool false if file not found, does not return if found - just send the file
1585 function assign_pluginfile($course,
1586 $cm,
1587 context $context,
1588 $filearea,
1589 $args,
1590 $forcedownload,
1591 array $options=array()) {
1592 global $CFG;
1594 if ($context->contextlevel != CONTEXT_MODULE) {
1595 return false;
1598 require_login($course, false, $cm);
1599 if (!has_capability('mod/assign:view', $context)) {
1600 return false;
1603 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1604 $assign = new assign($context, $cm, $course);
1606 if ($filearea !== ASSIGN_INTROATTACHMENT_FILEAREA) {
1607 return false;
1609 if (!$assign->show_intro()) {
1610 return false;
1613 $itemid = (int)array_shift($args);
1614 if ($itemid != 0) {
1615 return false;
1618 $relativepath = implode('/', $args);
1620 $fullpath = "/{$context->id}/mod_assign/$filearea/$itemid/$relativepath";
1622 $fs = get_file_storage();
1623 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1624 return false;
1626 send_stored_file($file, 0, 0, $forcedownload, $options);
1630 * Serve the grading panel as a fragment.
1632 * @param array $args List of named arguments for the fragment loader.
1633 * @return string
1635 function mod_assign_output_fragment_gradingpanel($args) {
1636 global $CFG;
1638 $context = $args['context'];
1640 if ($context->contextlevel != CONTEXT_MODULE) {
1641 return null;
1643 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1644 $assign = new assign($context, null, null);
1646 $userid = clean_param($args['userid'], PARAM_INT);
1647 $attemptnumber = clean_param($args['attemptnumber'], PARAM_INT);
1648 $formdata = array();
1649 if (!empty($args['jsonformdata'])) {
1650 $serialiseddata = json_decode($args['jsonformdata']);
1651 parse_str($serialiseddata, $formdata);
1653 $viewargs = array(
1654 'userid' => $userid,
1655 'attemptnumber' => $attemptnumber,
1656 'formdata' => $formdata
1659 return $assign->view('gradingpanel', $viewargs);
1663 * Check if the module has any update that affects the current user since a given time.
1665 * @param cm_info $cm course module data
1666 * @param int $from the time to check updates from
1667 * @param array $filter if we need to check only specific updates
1668 * @return stdClass an object with the different type of areas indicating if they were updated or not
1669 * @since Moodle 3.2
1671 function assign_check_updates_since(cm_info $cm, $from, $filter = array()) {
1672 global $DB, $USER, $CFG;
1673 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1675 $updates = new stdClass();
1676 $updates = course_check_module_updates_since($cm, $from, array(ASSIGN_INTROATTACHMENT_FILEAREA), $filter);
1678 // Check if there is a new submission by the user or new grades.
1679 $select = 'assignment = :id AND userid = :userid AND (timecreated > :since1 OR timemodified > :since2)';
1680 $params = array('id' => $cm->instance, 'userid' => $USER->id, 'since1' => $from, 'since2' => $from);
1681 $updates->submissions = (object) array('updated' => false);
1682 $submissions = $DB->get_records_select('assign_submission', $select, $params, '', 'id');
1683 if (!empty($submissions)) {
1684 $updates->submissions->updated = true;
1685 $updates->submissions->itemids = array_keys($submissions);
1688 $updates->grades = (object) array('updated' => false);
1689 $grades = $DB->get_records_select('assign_grades', $select, $params, '', 'id');
1690 if (!empty($grades)) {
1691 $updates->grades->updated = true;
1692 $updates->grades->itemids = array_keys($grades);
1695 // Now, teachers should see other students updates.
1696 if (has_capability('mod/assign:viewgrades', $cm->context)) {
1697 $params = array('id' => $cm->instance, 'since1' => $from, 'since2' => $from);
1698 $select = 'assignment = :id AND (timecreated > :since1 OR timemodified > :since2)';
1700 if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS) {
1701 $groupusers = array_keys(groups_get_activity_shared_group_members($cm));
1702 if (empty($groupusers)) {
1703 return $updates;
1705 list($insql, $inparams) = $DB->get_in_or_equal($groupusers, SQL_PARAMS_NAMED);
1706 $select .= ' AND userid ' . $insql;
1707 $params = array_merge($params, $inparams);
1710 $updates->usersubmissions = (object) array('updated' => false);
1711 $submissions = $DB->get_records_select('assign_submission', $select, $params, '', 'id');
1712 if (!empty($submissions)) {
1713 $updates->usersubmissions->updated = true;
1714 $updates->usersubmissions->itemids = array_keys($submissions);
1717 $updates->usergrades = (object) array('updated' => false);
1718 $grades = $DB->get_records_select('assign_grades', $select, $params, '', 'id');
1719 if (!empty($grades)) {
1720 $updates->usergrades->updated = true;
1721 $updates->usergrades->itemids = array_keys($grades);
1725 return $updates;