Merge branch 'MDL-48255-27' of git://github.com/lameze/moodle into MOODLE_27_STABLE
[moodle.git] / mod / assign / lib.php
blob721d581c19c14a82f234ec66e1199426fc4cd634
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 * Removes all grades from gradebook
93 * @param int $courseid The ID of the course to reset
94 * @param string $type Optional type of assignment to limit the reset to a particular assignment type
96 function assign_reset_gradebook($courseid, $type='') {
97 global $CFG, $DB;
99 $params = array('moduletype'=>'assign', 'courseid'=>$courseid);
100 $sql = 'SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
101 FROM {assign} a, {course_modules} cm, {modules} m
102 WHERE m.name=:moduletype AND m.id=cm.module AND cm.instance=a.id AND a.course=:courseid';
104 if ($assignments = $DB->get_records_sql($sql, $params)) {
105 foreach ($assignments as $assignment) {
106 assign_grade_item_update($assignment, 'reset');
112 * Implementation of the function for printing the form elements that control
113 * whether the course reset functionality affects the assignment.
114 * @param moodleform $mform form passed by reference
116 function assign_reset_course_form_definition(&$mform) {
117 $mform->addElement('header', 'assignheader', get_string('modulenameplural', 'assign'));
118 $name = get_string('deleteallsubmissions', 'assign');
119 $mform->addElement('advcheckbox', 'reset_assign_submissions', $name);
123 * Course reset form defaults.
124 * @param object $course
125 * @return array
127 function assign_reset_course_form_defaults($course) {
128 return array('reset_assign_submissions'=>1);
132 * Update an assignment instance
134 * This is done by calling the update_instance() method of the assignment type class
135 * @param stdClass $data
136 * @param stdClass $form - unused
137 * @return object
139 function assign_update_instance(stdClass $data, $form) {
140 global $CFG;
141 require_once($CFG->dirroot . '/mod/assign/locallib.php');
142 $context = context_module::instance($data->coursemodule);
143 $assignment = new assign($context, null, null);
144 return $assignment->update_instance($data);
148 * Return the list if Moodle features this module supports
150 * @param string $feature FEATURE_xx constant for requested feature
151 * @return mixed True if module supports feature, null if doesn't know
153 function assign_supports($feature) {
154 switch($feature) {
155 case FEATURE_GROUPS:
156 return true;
157 case FEATURE_GROUPINGS:
158 return true;
159 case FEATURE_GROUPMEMBERSONLY:
160 return true;
161 case FEATURE_MOD_INTRO:
162 return true;
163 case FEATURE_COMPLETION_TRACKS_VIEWS:
164 return true;
165 case FEATURE_COMPLETION_HAS_RULES:
166 return true;
167 case FEATURE_GRADE_HAS_GRADE:
168 return true;
169 case FEATURE_GRADE_OUTCOMES:
170 return true;
171 case FEATURE_BACKUP_MOODLE2:
172 return true;
173 case FEATURE_SHOW_DESCRIPTION:
174 return true;
175 case FEATURE_ADVANCED_GRADING:
176 return true;
177 case FEATURE_PLAGIARISM:
178 return true;
180 default:
181 return null;
186 * Lists all gradable areas for the advanced grading methods gramework
188 * @return array('string'=>'string') An array with area names as keys and descriptions as values
190 function assign_grading_areas_list() {
191 return array('submissions'=>get_string('submissions', 'assign'));
196 * extend an assigment navigation settings
198 * @param settings_navigation $settings
199 * @param navigation_node $navref
200 * @return void
202 function assign_extend_settings_navigation(settings_navigation $settings, navigation_node $navref) {
203 global $PAGE, $DB;
205 $cm = $PAGE->cm;
206 if (!$cm) {
207 return;
210 $context = $cm->context;
211 $course = $PAGE->course;
213 if (!$course) {
214 return;
217 // Link to gradebook.
218 if (has_capability('gradereport/grader:view', $cm->context) &&
219 has_capability('moodle/grade:viewall', $cm->context)) {
220 $link = new moodle_url('/grade/report/grader/index.php', array('id' => $course->id));
221 $linkname = get_string('viewgradebook', 'assign');
222 $node = $navref->add($linkname, $link, navigation_node::TYPE_SETTING);
225 // Link to download all submissions.
226 if (has_any_capability(array('mod/assign:grade', 'mod/assign:viewgrades'), $context)) {
227 $link = new moodle_url('/mod/assign/view.php', array('id' => $cm->id, 'action'=>'grading'));
228 $node = $navref->add(get_string('viewgrading', 'assign'), $link, navigation_node::TYPE_SETTING);
230 $link = new moodle_url('/mod/assign/view.php', array('id' => $cm->id, 'action'=>'downloadall'));
231 $node = $navref->add(get_string('downloadall', 'assign'), $link, navigation_node::TYPE_SETTING);
234 if (has_capability('mod/assign:revealidentities', $context)) {
235 $dbparams = array('id'=>$cm->instance);
236 $assignment = $DB->get_record('assign', $dbparams, 'blindmarking, revealidentities');
238 if ($assignment && $assignment->blindmarking && !$assignment->revealidentities) {
239 $urlparams = array('id' => $cm->id, 'action'=>'revealidentities');
240 $url = new moodle_url('/mod/assign/view.php', $urlparams);
241 $linkname = get_string('revealidentities', 'assign');
242 $node = $navref->add($linkname, $url, navigation_node::TYPE_SETTING);
248 * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
249 * for the course (see resource).
251 * Given a course_module object, this function returns any "extra" information that may be needed
252 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
254 * @param stdClass $coursemodule The coursemodule object (record).
255 * @return cached_cm_info An object on information that the courses
256 * will know about (most noticeably, an icon).
258 function assign_get_coursemodule_info($coursemodule) {
259 global $CFG, $DB;
261 $dbparams = array('id'=>$coursemodule->instance);
262 $fields = 'id, name, alwaysshowdescription, allowsubmissionsfromdate, intro, introformat';
263 if (! $assignment = $DB->get_record('assign', $dbparams, $fields)) {
264 return false;
267 $result = new cached_cm_info();
268 $result->name = $assignment->name;
269 if ($coursemodule->showdescription) {
270 if ($assignment->alwaysshowdescription || time() > $assignment->allowsubmissionsfromdate) {
271 // Convert intro to html. Do not filter cached version, filters run at display time.
272 $result->content = format_module_intro('assign', $assignment, $coursemodule->id, false);
275 return $result;
279 * Return a list of page types
280 * @param string $pagetype current page type
281 * @param stdClass $parentcontext Block's parent context
282 * @param stdClass $currentcontext Current context of block
284 function assign_page_type_list($pagetype, $parentcontext, $currentcontext) {
285 $modulepagetype = array(
286 'mod-assign-*' => get_string('page-mod-assign-x', 'assign'),
287 'mod-assign-view' => get_string('page-mod-assign-view', 'assign'),
289 return $modulepagetype;
293 * Print an overview of all assignments
294 * for the courses.
296 * @param mixed $courses The list of courses to print the overview for
297 * @param array $htmlarray The array of html to return
299 function assign_print_overview($courses, &$htmlarray) {
300 global $USER, $CFG, $DB;
302 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
303 return array();
306 if (!$assignments = get_all_instances_in_courses('assign', $courses)) {
307 return;
310 $assignmentids = array();
312 // Do assignment_base::isopen() here without loading the whole thing for speed.
313 foreach ($assignments as $key => $assignment) {
314 $time = time();
315 $isopen = false;
316 if ($assignment->duedate) {
317 $duedate = false;
318 if ($assignment->cutoffdate) {
319 $duedate = $assignment->cutoffdate;
321 if ($duedate) {
322 $isopen = ($assignment->allowsubmissionsfromdate <= $time && $time <= $duedate);
323 } else {
324 $isopen = ($assignment->allowsubmissionsfromdate <= $time);
327 if ($isopen) {
328 $assignmentids[] = $assignment->id;
332 if (empty($assignmentids)) {
333 // No assignments to look at - we're done.
334 return true;
337 // Definitely something to print, now include the constants we need.
338 require_once($CFG->dirroot . '/mod/assign/locallib.php');
340 $strduedate = get_string('duedate', 'assign');
341 $strcutoffdate = get_string('nosubmissionsacceptedafter', 'assign');
342 $strnolatesubmissions = get_string('nolatesubmissions', 'assign');
343 $strduedateno = get_string('duedateno', 'assign');
344 $strduedateno = get_string('duedateno', 'assign');
345 $strgraded = get_string('graded', 'assign');
346 $strnotgradedyet = get_string('notgradedyet', 'assign');
347 $strnotsubmittedyet = get_string('notsubmittedyet', 'assign');
348 $strsubmitted = get_string('submitted', 'assign');
349 $strassignment = get_string('modulename', 'assign');
350 $strreviewed = get_string('reviewed', 'assign');
352 // We do all possible database work here *outside* of the loop to ensure this scales.
353 list($sqlassignmentids, $assignmentidparams) = $DB->get_in_or_equal($assignmentids);
355 $mysubmissions = null;
356 $unmarkedsubmissions = null;
358 foreach ($assignments as $assignment) {
359 // Do not show assignments that are not open.
360 if (!in_array($assignment->id, $assignmentids)) {
361 continue;
363 $dimmedclass = '';
364 if (!$assignment->visible) {
365 $dimmedclass = ' class="dimmed"';
367 $href = $CFG->wwwroot . '/mod/assign/view.php?id=' . $assignment->coursemodule;
368 $str = '<div class="assign overview">' .
369 '<div class="name">' .
370 $strassignment . ': '.
371 '<a ' . $dimmedclass .
372 'title="' . $strassignment . '" ' .
373 'href="' . $href . '">' .
374 format_string($assignment->name) .
375 '</a></div>';
376 if ($assignment->duedate) {
377 $userdate = userdate($assignment->duedate);
378 $str .= '<div class="info">' . $strduedate . ': ' . $userdate . '</div>';
379 } else {
380 $str .= '<div class="info">' . $strduedateno . '</div>';
382 if ($assignment->cutoffdate) {
383 if ($assignment->cutoffdate == $assignment->duedate) {
384 $str .= '<div class="info">' . $strnolatesubmissions . '</div>';
385 } else {
386 $userdate = userdate($assignment->cutoffdate);
387 $str .= '<div class="info">' . $strcutoffdate . ': ' . $userdate . '</div>';
390 $context = context_module::instance($assignment->coursemodule);
391 if (has_capability('mod/assign:grade', $context)) {
392 if (!isset($unmarkedsubmissions)) {
393 $submissionmaxattempt = 'SELECT mxs.userid, MAX(mxs.attemptnumber) AS maxattempt, mxs.assignment
394 FROM {assign_submission} mxs
395 WHERE mxs.assignment ' . $sqlassignmentids . '
396 GROUP BY mxs.userid, mxs.assignment';
398 // Build up and array of unmarked submissions indexed by assignment id/ userid
399 // for use where the user has grading rights on assignment.
400 $dbparams = array_merge($assignmentidparams, array(ASSIGN_SUBMISSION_STATUS_SUBMITTED), $assignmentidparams);
401 $rs = $DB->get_recordset_sql('SELECT
402 s.assignment as assignment,
403 s.userid as userid,
404 s.id as id,
405 s.status as status,
406 g.timemodified as timegraded
407 FROM {assign_submission} s
408 LEFT JOIN ( ' . $submissionmaxattempt . ' ) smx ON
409 smx.userid = s.userid AND
410 smx.assignment = s.id
411 LEFT JOIN {assign_grades} g ON
412 s.userid = g.userid AND
413 s.assignment = g.assignment AND
414 g.attemptnumber = smx.maxattempt
415 WHERE
416 ( g.timemodified is NULL OR
417 s.timemodified > g.timemodified ) AND
418 s.timemodified IS NOT NULL AND
419 s.status = ? AND
420 s.attemptnumber = smx.maxattempt AND
421 s.assignment ' . $sqlassignmentids, $dbparams);
423 $unmarkedsubmissions = array();
424 foreach ($rs as $rd) {
425 $unmarkedsubmissions[$rd->assignment][$rd->userid] = $rd->id;
427 $rs->close();
430 // Count how many people can submit.
431 $submissions = 0;
432 if ($students = get_enrolled_users($context, 'mod/assign:view', 0, 'u.id')) {
433 foreach ($students as $student) {
434 if (isset($unmarkedsubmissions[$assignment->id][$student->id])) {
435 $submissions++;
440 if ($submissions) {
441 $urlparams = array('id'=>$assignment->coursemodule, 'action'=>'grading');
442 $url = new moodle_url('/mod/assign/view.php', $urlparams);
443 $str .= '<div class="details">' .
444 '<a href="' . $url . '">' .
445 get_string('submissionsnotgraded', 'assign', $submissions) .
446 '</a></div>';
449 if (has_capability('mod/assign:submit', $context)) {
450 if (!isset($mysubmissions)) {
452 // This is nasty because we only want the last attempt.
453 $submissionmaxattempt = 'SELECT mxs.userid, MAX(mxs.attemptnumber) AS maxattempt, mxs.assignment
454 FROM {assign_submission} mxs
455 WHERE mxs.assignment ' . $sqlassignmentids . '
456 AND mxs.userid = ?
457 GROUP BY mxs.userid, mxs.assignment';
459 // Get all user submissions, indexed by assignment id.
460 $dbparams = array_merge($assignmentidparams, array($USER->id, $USER->id, $USER->id), $assignmentidparams);
461 $mysubmissions = $DB->get_records_sql('SELECT
462 a.id AS assignment,
463 a.nosubmissions AS nosubmissions,
464 g.timemodified AS timemarked,
465 g.grader AS grader,
466 g.grade AS grade,
467 s.status AS status
468 FROM {assign} a
469 LEFT JOIN ( ' . $submissionmaxattempt . ' ) smx ON
470 smx.assignment = a.id
471 LEFT JOIN {assign_grades} g ON
472 g.assignment = a.id AND
473 g.userid = ? AND
474 g.attemptnumber = smx.maxattempt
475 LEFT JOIN {assign_submission} s ON
476 s.attemptnumber = smx.maxattempt AND
477 s.assignment = a.id AND
478 s.userid = ?
479 WHERE a.id ' . $sqlassignmentids, $dbparams);
482 $str .= '<div class="details">';
483 $str .= get_string('mysubmission', 'assign');
484 $submission = false;
485 if (isset($mysubmissions[$assignment->id])) {
486 $submission = $mysubmissions[$assignment->id];
488 if (!$submission || !$submission->status || $submission->status == 'draft') {
489 $str .= $strnotsubmittedyet;
490 } else if ($submission->nosubmissions) {
491 $str .= get_string('offline', 'assign');
492 } else {
493 $str .= get_string('submissionstatus_' . $submission->status, 'assign');
495 if (!$submission || !$submission->grade || $submission->grade < 0) {
496 $str .= ', ' . get_string('notgraded', 'assign');
497 } else {
498 $str .= ', ' . get_string('graded', 'assign');
500 $str .= '</div>';
502 $str .= '</div>';
503 if (empty($htmlarray[$assignment->course]['assign'])) {
504 $htmlarray[$assignment->course]['assign'] = $str;
505 } else {
506 $htmlarray[$assignment->course]['assign'] .= $str;
512 * Print recent activity from all assignments in a given course
514 * This is used by the recent activity block
515 * @param mixed $course the course to print activity for
516 * @param bool $viewfullnames boolean to determine whether to show full names or not
517 * @param int $timestart the time the rendering started
518 * @return bool true if activity was printed, false otherwise.
520 function assign_print_recent_activity($course, $viewfullnames, $timestart) {
521 global $CFG, $USER, $DB, $OUTPUT;
523 // Do not use log table if possible, it may be huge.
525 $dbparams = array($timestart, $course->id, 'assign');
526 $namefields = user_picture::fields('u', null, 'userid');
527 if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid,
528 $namefields
529 FROM {assign_submission} asb
530 JOIN {assign} a ON a.id = asb.assignment
531 JOIN {course_modules} cm ON cm.instance = a.id
532 JOIN {modules} md ON md.id = cm.module
533 JOIN {user} u ON u.id = asb.userid
534 WHERE asb.timemodified > ? AND
535 a.course = ? AND
536 md.name = ?
537 ORDER BY asb.timemodified ASC", $dbparams)) {
538 return false;
541 $modinfo = get_fast_modinfo($course);
542 $show = array();
543 $grader = array();
545 $showrecentsubmissions = get_config('assign', 'showrecentsubmissions');
547 foreach ($submissions as $submission) {
548 if (!array_key_exists($submission->cmid, $modinfo->get_cms())) {
549 continue;
551 $cm = $modinfo->get_cm($submission->cmid);
552 if (!$cm->uservisible) {
553 continue;
555 if ($submission->userid == $USER->id) {
556 $show[] = $submission;
557 continue;
560 $context = context_module::instance($submission->cmid);
561 // The act of submitting of assignment may be considered private -
562 // only graders will see it if specified.
563 if (empty($showrecentsubmissions)) {
564 if (!array_key_exists($cm->id, $grader)) {
565 $grader[$cm->id] = has_capability('moodle/grade:viewall', $context);
567 if (!$grader[$cm->id]) {
568 continue;
572 $groupmode = groups_get_activity_groupmode($cm, $course);
574 if ($groupmode == SEPARATEGROUPS &&
575 !has_capability('moodle/site:accessallgroups', $context)) {
576 if (isguestuser()) {
577 // Shortcut - guest user does not belong into any group.
578 continue;
581 // This will be slow - show only users that share group with me in this cm.
582 if (!$modinfo->get_groups($cm->groupingid)) {
583 continue;
585 $usersgroups = groups_get_all_groups($course->id, $submission->userid, $cm->groupingid);
586 if (is_array($usersgroups)) {
587 $usersgroups = array_keys($usersgroups);
588 $intersect = array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid));
589 if (empty($intersect)) {
590 continue;
594 $show[] = $submission;
597 if (empty($show)) {
598 return false;
601 echo $OUTPUT->heading(get_string('newsubmissions', 'assign').':', 3);
603 foreach ($show as $submission) {
604 $cm = $modinfo->get_cm($submission->cmid);
605 $link = $CFG->wwwroot.'/mod/assign/view.php?id='.$cm->id;
606 print_recent_activity_note($submission->timemodified,
607 $submission,
608 $cm->name,
609 $link,
610 false,
611 $viewfullnames);
614 return true;
618 * Returns all assignments since a given time.
620 * @param array $activities The activity information is returned in this array
621 * @param int $index The current index in the activities array
622 * @param int $timestart The earliest activity to show
623 * @param int $courseid Limit the search to this course
624 * @param int $cmid The course module id
625 * @param int $userid Optional user id
626 * @param int $groupid Optional group id
627 * @return void
629 function assign_get_recent_mod_activity(&$activities,
630 &$index,
631 $timestart,
632 $courseid,
633 $cmid,
634 $userid=0,
635 $groupid=0) {
636 global $CFG, $COURSE, $USER, $DB;
638 if ($COURSE->id == $courseid) {
639 $course = $COURSE;
640 } else {
641 $course = $DB->get_record('course', array('id'=>$courseid));
644 $modinfo = get_fast_modinfo($course);
646 $cm = $modinfo->get_cm($cmid);
647 $params = array();
648 if ($userid) {
649 $userselect = 'AND u.id = :userid';
650 $params['userid'] = $userid;
651 } else {
652 $userselect = '';
655 if ($groupid) {
656 $groupselect = 'AND gm.groupid = :groupid';
657 $groupjoin = 'JOIN {groups_members} gm ON gm.userid=u.id';
658 $params['groupid'] = $groupid;
659 } else {
660 $groupselect = '';
661 $groupjoin = '';
664 $params['cminstance'] = $cm->instance;
665 $params['timestart'] = $timestart;
667 $userfields = user_picture::fields('u', null, 'userid');
669 if (!$submissions = $DB->get_records_sql('SELECT asb.id, asb.timemodified, ' .
670 $userfields .
671 ' FROM {assign_submission} asb
672 JOIN {assign} a ON a.id = asb.assignment
673 JOIN {user} u ON u.id = asb.userid ' .
674 $groupjoin .
675 ' WHERE asb.timemodified > :timestart AND
676 a.id = :cminstance
677 ' . $userselect . ' ' . $groupselect .
678 ' ORDER BY asb.timemodified ASC', $params)) {
679 return;
682 $groupmode = groups_get_activity_groupmode($cm, $course);
683 $cmcontext = context_module::instance($cm->id);
684 $grader = has_capability('moodle/grade:viewall', $cmcontext);
685 $accessallgroups = has_capability('moodle/site:accessallgroups', $cmcontext);
686 $viewfullnames = has_capability('moodle/site:viewfullnames', $cmcontext);
689 $showrecentsubmissions = get_config('assign', 'showrecentsubmissions');
690 $show = array();
691 foreach ($submissions as $submission) {
692 if ($submission->userid == $USER->id) {
693 $show[] = $submission;
694 continue;
696 // The act of submitting of assignment may be considered private -
697 // only graders will see it if specified.
698 if (empty($showrecentsubmissions)) {
699 if (!$grader) {
700 continue;
704 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
705 if (isguestuser()) {
706 // Shortcut - guest user does not belong into any group.
707 continue;
710 // This will be slow - show only users that share group with me in this cm.
711 if (!$modinfo->get_groups($cm->groupingid)) {
712 continue;
714 $usersgroups = groups_get_all_groups($course->id, $submission->userid, $cm->groupingid);
715 if (is_array($usersgroups)) {
716 $usersgroups = array_keys($usersgroups);
717 $intersect = array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid));
718 if (empty($intersect)) {
719 continue;
723 $show[] = $submission;
726 if (empty($show)) {
727 return;
730 if ($grader) {
731 require_once($CFG->libdir.'/gradelib.php');
732 $userids = array();
733 foreach ($show as $id => $submission) {
734 $userids[] = $submission->userid;
736 $grades = grade_get_grades($courseid, 'mod', 'assign', $cm->instance, $userids);
739 $aname = format_string($cm->name, true);
740 foreach ($show as $submission) {
741 $activity = new stdClass();
743 $activity->type = 'assign';
744 $activity->cmid = $cm->id;
745 $activity->name = $aname;
746 $activity->sectionnum = $cm->sectionnum;
747 $activity->timestamp = $submission->timemodified;
748 $activity->user = new stdClass();
749 if ($grader) {
750 $activity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
753 $userfields = explode(',', user_picture::fields());
754 foreach ($userfields as $userfield) {
755 if ($userfield == 'id') {
756 // Aliased in SQL above.
757 $activity->user->{$userfield} = $submission->userid;
758 } else {
759 $activity->user->{$userfield} = $submission->{$userfield};
762 $activity->user->fullname = fullname($submission, $viewfullnames);
764 $activities[$index++] = $activity;
767 return;
771 * Print recent activity from all assignments in a given course
773 * This is used by course/recent.php
774 * @param stdClass $activity
775 * @param int $courseid
776 * @param bool $detail
777 * @param array $modnames
779 function assign_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
780 global $CFG, $OUTPUT;
782 echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
784 echo '<tr><td class="userpicture" valign="top">';
785 echo $OUTPUT->user_picture($activity->user);
786 echo '</td><td>';
788 if ($detail) {
789 $modname = $modnames[$activity->type];
790 echo '<div class="title">';
791 echo '<img src="' . $OUTPUT->pix_url('icon', 'assign') . '" '.
792 'class="icon" alt="' . $modname . '">';
793 echo '<a href="' . $CFG->wwwroot . '/mod/assign/view.php?id=' . $activity->cmid . '">';
794 echo $activity->name;
795 echo '</a>';
796 echo '</div>';
799 if (isset($activity->grade)) {
800 echo '<div class="grade">';
801 echo get_string('grade').': ';
802 echo $activity->grade;
803 echo '</div>';
806 echo '<div class="user">';
807 echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->id}&amp;course=$courseid\">";
808 echo "{$activity->user->fullname}</a> - " . userdate($activity->timestamp);
809 echo '</div>';
811 echo '</td></tr></table>';
815 * Checks if a scale is being used by an assignment.
817 * This is used by the backup code to decide whether to back up a scale
818 * @param int $assignmentid
819 * @param int $scaleid
820 * @return boolean True if the scale is used by the assignment
822 function assign_scale_used($assignmentid, $scaleid) {
823 global $DB;
825 $return = false;
826 $rec = $DB->get_record('assign', array('id'=>$assignmentid, 'grade'=>-$scaleid));
828 if (!empty($rec) && !empty($scaleid)) {
829 $return = true;
832 return $return;
836 * Checks if scale is being used by any instance of assignment
838 * This is used to find out if scale used anywhere
839 * @param int $scaleid
840 * @return boolean True if the scale is used by any assignment
842 function assign_scale_used_anywhere($scaleid) {
843 global $DB;
845 if ($scaleid and $DB->record_exists('assign', array('grade'=>-$scaleid))) {
846 return true;
847 } else {
848 return false;
853 * List the actions that correspond to a view of this module.
854 * This is used by the participation report.
856 * Note: This is not used by new logging system. Event with
857 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
858 * be considered as view action.
860 * @return array
862 function assign_get_view_actions() {
863 return array('view submission', 'view feedback');
867 * List the actions that correspond to a post of this module.
868 * This is used by the participation report.
870 * Note: This is not used by new logging system. Event with
871 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
872 * will be considered as post action.
874 * @return array
876 function assign_get_post_actions() {
877 return array('upload', 'submit', 'submit for grading');
881 * Call cron on the assign module.
883 function assign_cron() {
884 global $CFG;
886 require_once($CFG->dirroot . '/mod/assign/locallib.php');
887 assign::cron();
889 $plugins = core_component::get_plugin_list('assignsubmission');
891 foreach ($plugins as $name => $plugin) {
892 $disabled = get_config('assignsubmission_' . $name, 'disabled');
893 if (!$disabled) {
894 $class = 'assign_submission_' . $name;
895 require_once($CFG->dirroot . '/mod/assign/submission/' . $name . '/locallib.php');
896 $class::cron();
899 $plugins = core_component::get_plugin_list('assignfeedback');
901 foreach ($plugins as $name => $plugin) {
902 $disabled = get_config('assignfeedback_' . $name, 'disabled');
903 if (!$disabled) {
904 $class = 'assign_feedback_' . $name;
905 require_once($CFG->dirroot . '/mod/assign/feedback/' . $name . '/locallib.php');
906 $class::cron();
910 return true;
914 * Returns all other capabilities used by this module.
915 * @return array Array of capability strings
917 function assign_get_extra_capabilities() {
918 return array('gradereport/grader:view',
919 'moodle/grade:viewall',
920 'moodle/site:viewfullnames',
921 'moodle/site:config');
925 * Create grade item for given assignment.
927 * @param stdClass $assign record with extra cmidnumber
928 * @param array $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
929 * @return int 0 if ok, error code otherwise
931 function assign_grade_item_update($assign, $grades=null) {
932 global $CFG;
933 require_once($CFG->libdir.'/gradelib.php');
935 if (!isset($assign->courseid)) {
936 $assign->courseid = $assign->course;
939 $params = array('itemname'=>$assign->name, 'idnumber'=>$assign->cmidnumber);
941 // Check if feedback plugin for gradebook is enabled, if yes then
942 // gradetype = GRADE_TYPE_TEXT else GRADE_TYPE_NONE.
943 $gradefeedbackenabled = false;
945 if (isset($assign->gradefeedbackenabled)) {
946 $gradefeedbackenabled = $assign->gradefeedbackenabled;
947 } else if ($assign->grade == 0) { // Grade feedback is needed only when grade == 0.
948 require_once($CFG->dirroot . '/mod/assign/locallib.php');
949 $mod = get_coursemodule_from_instance('assign', $assign->id, $assign->courseid);
950 $cm = context_module::instance($mod->id);
951 $assignment = new assign($cm, null, null);
952 $gradefeedbackenabled = $assignment->is_gradebook_feedback_enabled();
955 if ($assign->grade > 0) {
956 $params['gradetype'] = GRADE_TYPE_VALUE;
957 $params['grademax'] = $assign->grade;
958 $params['grademin'] = 0;
960 } else if ($assign->grade < 0) {
961 $params['gradetype'] = GRADE_TYPE_SCALE;
962 $params['scaleid'] = -$assign->grade;
964 } else if ($gradefeedbackenabled) {
965 // $assign->grade == 0 and feedback enabled.
966 $params['gradetype'] = GRADE_TYPE_TEXT;
967 } else {
968 // $assign->grade == 0 and no feedback enabled.
969 $params['gradetype'] = GRADE_TYPE_NONE;
972 if ($grades === 'reset') {
973 $params['reset'] = true;
974 $grades = null;
977 return grade_update('mod/assign',
978 $assign->courseid,
979 'mod',
980 'assign',
981 $assign->id,
983 $grades,
984 $params);
988 * Return grade for given user or all users.
990 * @param stdClass $assign record of assign with an additional cmidnumber
991 * @param int $userid optional user id, 0 means all users
992 * @return array array of grades, false if none
994 function assign_get_user_grades($assign, $userid=0) {
995 global $CFG;
997 require_once($CFG->dirroot . '/mod/assign/locallib.php');
999 $cm = get_coursemodule_from_instance('assign', $assign->id, 0, false, MUST_EXIST);
1000 $context = context_module::instance($cm->id);
1001 $assignment = new assign($context, null, null);
1002 $assignment->set_instance($assign);
1003 return $assignment->get_user_grades_for_gradebook($userid);
1007 * Update activity grades.
1009 * @param stdClass $assign database record
1010 * @param int $userid specific user only, 0 means all
1011 * @param bool $nullifnone - not used
1013 function assign_update_grades($assign, $userid=0, $nullifnone=true) {
1014 global $CFG;
1015 require_once($CFG->libdir.'/gradelib.php');
1017 if ($assign->grade == 0) {
1018 assign_grade_item_update($assign);
1020 } else if ($grades = assign_get_user_grades($assign, $userid)) {
1021 foreach ($grades as $k => $v) {
1022 if ($v->rawgrade == -1) {
1023 $grades[$k]->rawgrade = null;
1026 assign_grade_item_update($assign, $grades);
1028 } else {
1029 assign_grade_item_update($assign);
1034 * List the file areas that can be browsed.
1036 * @param stdClass $course
1037 * @param stdClass $cm
1038 * @param stdClass $context
1039 * @return array
1041 function assign_get_file_areas($course, $cm, $context) {
1042 global $CFG;
1043 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1044 $areas = array();
1046 $assignment = new assign($context, $cm, $course);
1047 foreach ($assignment->get_submission_plugins() as $plugin) {
1048 if ($plugin->is_visible()) {
1049 $pluginareas = $plugin->get_file_areas();
1051 if ($pluginareas) {
1052 $areas = array_merge($areas, $pluginareas);
1056 foreach ($assignment->get_feedback_plugins() as $plugin) {
1057 if ($plugin->is_visible()) {
1058 $pluginareas = $plugin->get_file_areas();
1060 if ($pluginareas) {
1061 $areas = array_merge($areas, $pluginareas);
1066 return $areas;
1070 * File browsing support for assign module.
1072 * @param file_browser $browser
1073 * @param object $areas
1074 * @param object $course
1075 * @param object $cm
1076 * @param object $context
1077 * @param string $filearea
1078 * @param int $itemid
1079 * @param string $filepath
1080 * @param string $filename
1081 * @return object file_info instance or null if not found
1083 function assign_get_file_info($browser,
1084 $areas,
1085 $course,
1086 $cm,
1087 $context,
1088 $filearea,
1089 $itemid,
1090 $filepath,
1091 $filename) {
1092 global $CFG;
1093 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1095 if ($context->contextlevel != CONTEXT_MODULE) {
1096 return null;
1099 $fs = get_file_storage();
1100 $filepath = is_null($filepath) ? '/' : $filepath;
1101 $filename = is_null($filename) ? '.' : $filename;
1103 // Need to find the plugin this belongs to.
1104 $assignment = new assign($context, $cm, $course);
1105 $pluginowner = null;
1106 foreach ($assignment->get_submission_plugins() as $plugin) {
1107 if ($plugin->is_visible()) {
1108 $pluginareas = $plugin->get_file_areas();
1110 if (array_key_exists($filearea, $pluginareas)) {
1111 $pluginowner = $plugin;
1112 break;
1116 if (!$pluginowner) {
1117 foreach ($assignment->get_feedback_plugins() as $plugin) {
1118 if ($plugin->is_visible()) {
1119 $pluginareas = $plugin->get_file_areas();
1121 if (array_key_exists($filearea, $pluginareas)) {
1122 $pluginowner = $plugin;
1123 break;
1129 if (!$pluginowner) {
1130 return null;
1133 $result = $pluginowner->get_file_info($browser, $filearea, $itemid, $filepath, $filename);
1134 return $result;
1138 * Prints the complete info about a user's interaction with an assignment.
1140 * @param stdClass $course
1141 * @param stdClass $user
1142 * @param stdClass $coursemodule
1143 * @param stdClass $assign the database assign record
1145 * This prints the submission summary and feedback summary for this student.
1147 function assign_user_complete($course, $user, $coursemodule, $assign) {
1148 global $CFG;
1149 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1151 $context = context_module::instance($coursemodule->id);
1153 $assignment = new assign($context, $coursemodule, $course);
1155 echo $assignment->view_student_summary($user, false);
1159 * Print the grade information for the assignment for this user.
1161 * @param stdClass $course
1162 * @param stdClass $user
1163 * @param stdClass $coursemodule
1164 * @param stdClass $assignment
1166 function assign_user_outline($course, $user, $coursemodule, $assignment) {
1167 global $CFG;
1168 require_once($CFG->libdir.'/gradelib.php');
1169 require_once($CFG->dirroot.'/grade/grading/lib.php');
1171 $gradinginfo = grade_get_grades($course->id,
1172 'mod',
1173 'assign',
1174 $assignment->id,
1175 $user->id);
1177 $gradingitem = $gradinginfo->items[0];
1178 $gradebookgrade = $gradingitem->grades[$user->id];
1180 if (empty($gradebookgrade->str_long_grade)) {
1181 return null;
1183 $result = new stdClass();
1184 $result->info = get_string('outlinegrade', 'assign', $gradebookgrade->str_long_grade);
1185 $result->time = $gradebookgrade->dategraded;
1187 return $result;
1191 * Obtains the automatic completion state for this module based on any conditions
1192 * in assign settings.
1194 * @param object $course Course
1195 * @param object $cm Course-module
1196 * @param int $userid User ID
1197 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
1198 * @return bool True if completed, false if not, $type if conditions not set.
1200 function assign_get_completion_state($course, $cm, $userid, $type) {
1201 global $CFG, $DB;
1202 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1204 $assign = new assign(null, $cm, $course);
1206 // If completion option is enabled, evaluate it and return true/false.
1207 if ($assign->get_instance()->completionsubmit) {
1208 $dbparams = array('assignment'=>$assign->get_instance()->id, 'userid'=>$userid);
1209 $submission = $DB->get_record('assign_submission', $dbparams, '*', IGNORE_MISSING);
1210 return $submission && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1211 } else {
1212 // Completion option is not enabled so just return $type.
1213 return $type;