MDL-44732 add cli script for execution of scheduled tasks
[moodle.git] / mod / assign / lib.php
blob42dff0abe798f20e2d74173999d9607df60c8461
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 // Build up and array of unmarked submissions indexed by assignment id/ userid
394 // for use where the user has grading rights on assignment.
395 $dbparams = array_merge(array(ASSIGN_SUBMISSION_STATUS_SUBMITTED), $assignmentidparams);
396 $rs = $DB->get_recordset_sql('SELECT
397 s.assignment as assignment,
398 s.userid as userid,
399 s.id as id,
400 s.status as status,
401 g.timemodified as timegraded
402 FROM {assign_submission} s
403 LEFT JOIN {assign_grades} g ON
404 s.userid = g.userid AND
405 s.assignment = g.assignment
406 WHERE
407 ( g.timemodified is NULL OR
408 s.timemodified > g.timemodified ) AND
409 s.timemodified IS NOT NULL AND
410 s.status = ? AND
411 s.assignment ' . $sqlassignmentids, $dbparams);
413 $unmarkedsubmissions = array();
414 foreach ($rs as $rd) {
415 $unmarkedsubmissions[$rd->assignment][$rd->userid] = $rd->id;
417 $rs->close();
420 // Count how many people can submit.
421 $submissions = 0;
422 if ($students = get_enrolled_users($context, 'mod/assign:view', 0, 'u.id')) {
423 foreach ($students as $student) {
424 if (isset($unmarkedsubmissions[$assignment->id][$student->id])) {
425 $submissions++;
430 if ($submissions) {
431 $urlparams = array('id'=>$assignment->coursemodule, 'action'=>'grading');
432 $url = new moodle_url('/mod/assign/view.php', $urlparams);
433 $str .= '<div class="details">' .
434 '<a href="' . $url . '">' .
435 get_string('submissionsnotgraded', 'assign', $submissions) .
436 '</a></div>';
439 if (has_capability('mod/assign:submit', $context)) {
440 if (!isset($mysubmissions)) {
441 // Get all user submissions, indexed by assignment id.
442 $dbparams = array_merge(array($USER->id, $USER->id), $assignmentidparams);
443 $mysubmissions = $DB->get_records_sql('SELECT
444 a.id AS assignment,
445 a.nosubmissions AS nosubmissions,
446 g.timemodified AS timemarked,
447 g.grader AS grader,
448 g.grade AS grade,
449 s.status AS status
450 FROM {assign} a
451 LEFT JOIN {assign_grades} g ON
452 g.assignment = a.id AND
453 g.userid = ?
454 LEFT JOIN {assign_submission} s ON
455 s.assignment = a.id AND
456 s.userid = ?
457 WHERE a.id ' . $sqlassignmentids, $dbparams);
460 $str .= '<div class="details">';
461 $str .= get_string('mysubmission', 'assign');
462 $submission = $mysubmissions[$assignment->id];
463 if ($submission->nosubmissions) {
464 $str .= get_string('offline', 'assign');
465 } else if (!$submission->status || $submission->status == 'draft') {
466 $str .= $strnotsubmittedyet;
467 } else {
468 $str .= get_string('submissionstatus_' . $submission->status, 'assign');
470 if (!$submission->grade || $submission->grade < 0) {
471 $str .= ', ' . get_string('notgraded', 'assign');
472 } else {
473 $str .= ', ' . get_string('graded', 'assign');
475 $str .= '</div>';
477 $str .= '</div>';
478 if (empty($htmlarray[$assignment->course]['assign'])) {
479 $htmlarray[$assignment->course]['assign'] = $str;
480 } else {
481 $htmlarray[$assignment->course]['assign'] .= $str;
487 * Print recent activity from all assignments in a given course
489 * This is used by the recent activity block
490 * @param mixed $course the course to print activity for
491 * @param bool $viewfullnames boolean to determine whether to show full names or not
492 * @param int $timestart the time the rendering started
493 * @return bool true if activity was printed, false otherwise.
495 function assign_print_recent_activity($course, $viewfullnames, $timestart) {
496 global $CFG, $USER, $DB, $OUTPUT;
498 // Do not use log table if possible, it may be huge.
500 $dbparams = array($timestart, $course->id, 'assign');
501 $namefields = user_picture::fields('u', null, 'userid');
502 if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid,
503 $namefields
504 FROM {assign_submission} asb
505 JOIN {assign} a ON a.id = asb.assignment
506 JOIN {course_modules} cm ON cm.instance = a.id
507 JOIN {modules} md ON md.id = cm.module
508 JOIN {user} u ON u.id = asb.userid
509 WHERE asb.timemodified > ? AND
510 a.course = ? AND
511 md.name = ?
512 ORDER BY asb.timemodified ASC", $dbparams)) {
513 return false;
516 $modinfo = get_fast_modinfo($course);
517 $show = array();
518 $grader = array();
520 $showrecentsubmissions = get_config('mod_assign', 'showrecentsubmissions');
522 foreach ($submissions as $submission) {
523 if (!array_key_exists($submission->cmid, $modinfo->get_cms())) {
524 continue;
526 $cm = $modinfo->get_cm($submission->cmid);
527 if (!$cm->uservisible) {
528 continue;
530 if ($submission->userid == $USER->id) {
531 $show[] = $submission;
532 continue;
535 $context = context_module::instance($submission->cmid);
536 // The act of submitting of assignment may be considered private -
537 // only graders will see it if specified.
538 if (empty($showrecentsubmissions)) {
539 if (!array_key_exists($cm->id, $grader)) {
540 $grader[$cm->id] = has_capability('moodle/grade:viewall', $context);
542 if (!$grader[$cm->id]) {
543 continue;
547 $groupmode = groups_get_activity_groupmode($cm, $course);
549 if ($groupmode == SEPARATEGROUPS &&
550 !has_capability('moodle/site:accessallgroups', $context)) {
551 if (isguestuser()) {
552 // Shortcut - guest user does not belong into any group.
553 continue;
556 if (is_null($modinfo->get_groups())) {
557 // Load all my groups and cache it in modinfo.
558 $modinfo->groups = groups_get_user_groups($course->id);
561 // This will be slow - show only users that share group with me in this cm.
562 if (empty($modinfo->groups[$cm->id])) {
563 continue;
565 $usersgroups = groups_get_all_groups($course->id, $submission->userid, $cm->groupingid);
566 if (is_array($usersgroups)) {
567 $usersgroups = array_keys($usersgroups);
568 $intersect = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
569 if (empty($intersect)) {
570 continue;
574 $show[] = $submission;
577 if (empty($show)) {
578 return false;
581 echo $OUTPUT->heading(get_string('newsubmissions', 'assign').':', 3);
583 foreach ($show as $submission) {
584 $cm = $modinfo->get_cm($submission->cmid);
585 $link = $CFG->wwwroot.'/mod/assign/view.php?id='.$cm->id;
586 print_recent_activity_note($submission->timemodified,
587 $submission,
588 $cm->name,
589 $link,
590 false,
591 $viewfullnames);
594 return true;
598 * Returns all assignments since a given time.
600 * @param array $activities The activity information is returned in this array
601 * @param int $index The current index in the activities array
602 * @param int $timestart The earliest activity to show
603 * @param int $courseid Limit the search to this course
604 * @param int $cmid The course module id
605 * @param int $userid Optional user id
606 * @param int $groupid Optional group id
607 * @return void
609 function assign_get_recent_mod_activity(&$activities,
610 &$index,
611 $timestart,
612 $courseid,
613 $cmid,
614 $userid=0,
615 $groupid=0) {
616 global $CFG, $COURSE, $USER, $DB;
618 if ($COURSE->id == $courseid) {
619 $course = $COURSE;
620 } else {
621 $course = $DB->get_record('course', array('id'=>$courseid));
624 $modinfo = get_fast_modinfo($course);
626 $cm = $modinfo->get_cm($cmid);
627 $params = array();
628 if ($userid) {
629 $userselect = 'AND u.id = :userid';
630 $params['userid'] = $userid;
631 } else {
632 $userselect = '';
635 if ($groupid) {
636 $groupselect = 'AND gm.groupid = :groupid';
637 $groupjoin = 'JOIN {groups_members} gm ON gm.userid=u.id';
638 $params['groupid'] = $groupid;
639 } else {
640 $groupselect = '';
641 $groupjoin = '';
644 $params['cminstance'] = $cm->instance;
645 $params['timestart'] = $timestart;
647 $userfields = user_picture::fields('u', null, 'userid');
649 if (!$submissions = $DB->get_records_sql('SELECT asb.id, asb.timemodified, ' .
650 $userfields .
651 ' FROM {assign_submission} asb
652 JOIN {assign} a ON a.id = asb.assignment
653 JOIN {user} u ON u.id = asb.userid ' .
654 $groupjoin .
655 ' WHERE asb.timemodified > :timestart AND
656 a.id = :cminstance
657 ' . $userselect . ' ' . $groupselect .
658 ' ORDER BY asb.timemodified ASC', $params)) {
659 return;
662 $groupmode = groups_get_activity_groupmode($cm, $course);
663 $cmcontext = context_module::instance($cm->id);
664 $grader = has_capability('moodle/grade:viewall', $cmcontext);
665 $accessallgroups = has_capability('moodle/site:accessallgroups', $cmcontext);
666 $viewfullnames = has_capability('moodle/site:viewfullnames', $cmcontext);
668 if (is_null($modinfo->get_groups())) {
669 // Load all my groups and cache it in modinfo.
670 $modinfo->groups = groups_get_user_groups($course->id);
673 $showrecentsubmissions = get_config('mod_assign', 'showrecentsubmissions');
674 $show = array();
675 $usersgroups = groups_get_all_groups($course->id, $USER->id, $cm->groupingid);
676 if (is_array($usersgroups)) {
677 $usersgroups = array_keys($usersgroups);
679 foreach ($submissions as $submission) {
680 if ($submission->userid == $USER->id) {
681 $show[] = $submission;
682 continue;
684 // The act of submitting of assignment may be considered private -
685 // only graders will see it if specified.
686 if (empty($showrecentsubmissions)) {
687 if (!$grader) {
688 continue;
692 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
693 if (isguestuser()) {
694 // Shortcut - guest user does not belong into any group.
695 continue;
698 // This will be slow - show only users that share group with me in this cm.
699 if (empty($modinfo->groups[$cm->id])) {
700 continue;
702 if (is_array($usersgroups)) {
703 $intersect = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
704 if (empty($intersect)) {
705 continue;
709 $show[] = $submission;
712 if (empty($show)) {
713 return;
716 if ($grader) {
717 require_once($CFG->libdir.'/gradelib.php');
718 $userids = array();
719 foreach ($show as $id => $submission) {
720 $userids[] = $submission->userid;
722 $grades = grade_get_grades($courseid, 'mod', 'assign', $cm->instance, $userids);
725 $aname = format_string($cm->name, true);
726 foreach ($show as $submission) {
727 $activity = new stdClass();
729 $activity->type = 'assign';
730 $activity->cmid = $cm->id;
731 $activity->name = $aname;
732 $activity->sectionnum = $cm->sectionnum;
733 $activity->timestamp = $submission->timemodified;
734 $activity->user = new stdClass();
735 if ($grader) {
736 $activity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
739 $userfields = explode(',', user_picture::fields());
740 foreach ($userfields as $userfield) {
741 if ($userfield == 'id') {
742 // Aliased in SQL above.
743 $activity->user->{$userfield} = $submission->userid;
744 } else {
745 $activity->user->{$userfield} = $submission->{$userfield};
748 $activity->user->fullname = fullname($submission, $viewfullnames);
750 $activities[$index++] = $activity;
753 return;
757 * Print recent activity from all assignments in a given course
759 * This is used by course/recent.php
760 * @param stdClass $activity
761 * @param int $courseid
762 * @param bool $detail
763 * @param array $modnames
765 function assign_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
766 global $CFG, $OUTPUT;
768 echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
770 echo '<tr><td class="userpicture" valign="top">';
771 echo $OUTPUT->user_picture($activity->user);
772 echo '</td><td>';
774 if ($detail) {
775 $modname = $modnames[$activity->type];
776 echo '<div class="title">';
777 echo '<img src="' . $OUTPUT->pix_url('icon', 'assign') . '" '.
778 'class="icon" alt="' . $modname . '">';
779 echo '<a href="' . $CFG->wwwroot . '/mod/assign/view.php?id=' . $activity->cmid . '">';
780 echo $activity->name;
781 echo '</a>';
782 echo '</div>';
785 if (isset($activity->grade)) {
786 echo '<div class="grade">';
787 echo get_string('grade').': ';
788 echo $activity->grade;
789 echo '</div>';
792 echo '<div class="user">';
793 echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->id}&amp;course=$courseid\">";
794 echo "{$activity->user->fullname}</a> - " . userdate($activity->timestamp);
795 echo '</div>';
797 echo '</td></tr></table>';
801 * Checks if a scale is being used by an assignment.
803 * This is used by the backup code to decide whether to back up a scale
804 * @param int $assignmentid
805 * @param int $scaleid
806 * @return boolean True if the scale is used by the assignment
808 function assign_scale_used($assignmentid, $scaleid) {
809 global $DB;
811 $return = false;
812 $rec = $DB->get_record('assign', array('id'=>$assignmentid, 'grade'=>-$scaleid));
814 if (!empty($rec) && !empty($scaleid)) {
815 $return = true;
818 return $return;
822 * Checks if scale is being used by any instance of assignment
824 * This is used to find out if scale used anywhere
825 * @param int $scaleid
826 * @return boolean True if the scale is used by any assignment
828 function assign_scale_used_anywhere($scaleid) {
829 global $DB;
831 if ($scaleid and $DB->record_exists('assign', array('grade'=>-$scaleid))) {
832 return true;
833 } else {
834 return false;
839 * List the actions that correspond to a view of this module.
840 * This is used by the participation report.
841 * @return array
843 function assign_get_view_actions() {
844 return array('view submission', 'view feedback');
848 * List the actions that correspond to a post of this module.
849 * This is used by the participation report.
850 * @return array
852 function assign_get_post_actions() {
853 return array('upload', 'submit', 'submit for grading');
857 * Call cron on the assign module.
859 function assign_cron() {
860 global $CFG;
862 require_once($CFG->dirroot . '/mod/assign/locallib.php');
863 assign::cron();
865 $plugins = core_component::get_plugin_list('assignsubmission');
867 foreach ($plugins as $name => $plugin) {
868 $disabled = get_config('assignsubmission_' . $name, 'disabled');
869 if (!$disabled) {
870 $class = 'assign_submission_' . $name;
871 require_once($CFG->dirroot . '/mod/assign/submission/' . $name . '/locallib.php');
872 $class::cron();
875 $plugins = core_component::get_plugin_list('assignfeedback');
877 foreach ($plugins as $name => $plugin) {
878 $disabled = get_config('assignfeedback_' . $name, 'disabled');
879 if (!$disabled) {
880 $class = 'assign_feedback_' . $name;
881 require_once($CFG->dirroot . '/mod/assign/feedback/' . $name . '/locallib.php');
882 $class::cron();
888 * Returns all other capabilities used by this module.
889 * @return array Array of capability strings
891 function assign_get_extra_capabilities() {
892 return array('gradereport/grader:view',
893 'moodle/grade:viewall',
894 'moodle/site:viewfullnames',
895 'moodle/site:config');
899 * Create grade item for given assignment.
901 * @param stdClass $assign record with extra cmidnumber
902 * @param array $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
903 * @return int 0 if ok, error code otherwise
905 function assign_grade_item_update($assign, $grades=null) {
906 global $CFG;
907 require_once($CFG->libdir.'/gradelib.php');
909 if (!isset($assign->courseid)) {
910 $assign->courseid = $assign->course;
913 $params = array('itemname'=>$assign->name, 'idnumber'=>$assign->cmidnumber);
915 // Check if feedback plugin for gradebook is enabled, if yes then
916 // gradetype = GRADE_TYPE_TEXT else GRADE_TYPE_NONE.
917 $gradefeedbackenabled = false;
919 if (isset($assign->gradefeedbackenabled)) {
920 $gradefeedbackenabled = $assign->gradefeedbackenabled;
921 } else if ($assign->grade == 0) { // Grade feedback is needed only when grade == 0.
922 $mod = get_coursemodule_from_instance('assign', $assign->id, $assign->courseid);
923 $cm = context_module::instance($mod->id);
924 $assignment = new assign($cm, null, null);
925 $gradefeedbackenabled = $assignment->is_gradebook_feedback_enabled();
928 if ($assign->grade > 0) {
929 $params['gradetype'] = GRADE_TYPE_VALUE;
930 $params['grademax'] = $assign->grade;
931 $params['grademin'] = 0;
933 } else if ($assign->grade < 0) {
934 $params['gradetype'] = GRADE_TYPE_SCALE;
935 $params['scaleid'] = -$assign->grade;
937 } else if ($gradefeedbackenabled) {
938 // $assign->grade == 0 and feedback enabled.
939 $params['gradetype'] = GRADE_TYPE_TEXT;
940 } else {
941 // $assign->grade == 0 and no feedback enabled.
942 $params['gradetype'] = GRADE_TYPE_NONE;
945 if ($grades === 'reset') {
946 $params['reset'] = true;
947 $grades = null;
950 return grade_update('mod/assign',
951 $assign->courseid,
952 'mod',
953 'assign',
954 $assign->id,
956 $grades,
957 $params);
961 * Return grade for given user or all users.
963 * @param stdClass $assign record of assign with an additional cmidnumber
964 * @param int $userid optional user id, 0 means all users
965 * @return array array of grades, false if none
967 function assign_get_user_grades($assign, $userid=0) {
968 global $CFG;
970 require_once($CFG->dirroot . '/mod/assign/locallib.php');
972 $cm = get_coursemodule_from_instance('assign', $assign->id, 0, false, MUST_EXIST);
973 $context = context_module::instance($cm->id);
974 $assignment = new assign($context, null, null);
975 $assignment->set_instance($assign);
976 return $assignment->get_user_grades_for_gradebook($userid);
980 * Update activity grades.
982 * @param stdClass $assign database record
983 * @param int $userid specific user only, 0 means all
984 * @param bool $nullifnone - not used
986 function assign_update_grades($assign, $userid=0, $nullifnone=true) {
987 global $CFG;
988 require_once($CFG->libdir.'/gradelib.php');
990 if ($assign->grade == 0) {
991 assign_grade_item_update($assign);
993 } else if ($grades = assign_get_user_grades($assign, $userid)) {
994 foreach ($grades as $k => $v) {
995 if ($v->rawgrade == -1) {
996 $grades[$k]->rawgrade = null;
999 assign_grade_item_update($assign, $grades);
1001 } else {
1002 assign_grade_item_update($assign);
1007 * List the file areas that can be browsed.
1009 * @param stdClass $course
1010 * @param stdClass $cm
1011 * @param stdClass $context
1012 * @return array
1014 function assign_get_file_areas($course, $cm, $context) {
1015 global $CFG;
1016 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1017 $areas = array();
1019 $assignment = new assign($context, $cm, $course);
1020 foreach ($assignment->get_submission_plugins() as $plugin) {
1021 if ($plugin->is_visible()) {
1022 $pluginareas = $plugin->get_file_areas();
1024 if ($pluginareas) {
1025 $areas = array_merge($areas, $pluginareas);
1029 foreach ($assignment->get_feedback_plugins() as $plugin) {
1030 if ($plugin->is_visible()) {
1031 $pluginareas = $plugin->get_file_areas();
1033 if ($pluginareas) {
1034 $areas = array_merge($areas, $pluginareas);
1039 return $areas;
1043 * File browsing support for assign module.
1045 * @param file_browser $browser
1046 * @param object $areas
1047 * @param object $course
1048 * @param object $cm
1049 * @param object $context
1050 * @param string $filearea
1051 * @param int $itemid
1052 * @param string $filepath
1053 * @param string $filename
1054 * @return object file_info instance or null if not found
1056 function assign_get_file_info($browser,
1057 $areas,
1058 $course,
1059 $cm,
1060 $context,
1061 $filearea,
1062 $itemid,
1063 $filepath,
1064 $filename) {
1065 global $CFG;
1066 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1068 if ($context->contextlevel != CONTEXT_MODULE) {
1069 return null;
1072 $fs = get_file_storage();
1073 $filepath = is_null($filepath) ? '/' : $filepath;
1074 $filename = is_null($filename) ? '.' : $filename;
1076 // Need to find the plugin this belongs to.
1077 $assignment = new assign($context, $cm, $course);
1078 $pluginowner = null;
1079 foreach ($assignment->get_submission_plugins() as $plugin) {
1080 if ($plugin->is_visible()) {
1081 $pluginareas = $plugin->get_file_areas();
1083 if (array_key_exists($filearea, $pluginareas)) {
1084 $pluginowner = $plugin;
1085 break;
1089 if (!$pluginowner) {
1090 foreach ($assignment->get_feedback_plugins() as $plugin) {
1091 if ($plugin->is_visible()) {
1092 $pluginareas = $plugin->get_file_areas();
1094 if (array_key_exists($filearea, $pluginareas)) {
1095 $pluginowner = $plugin;
1096 break;
1102 if (!$pluginowner) {
1103 return null;
1106 $result = $pluginowner->get_file_info($browser, $filearea, $itemid, $filepath, $filename);
1107 return $result;
1111 * Prints the complete info about a user's interaction with an assignment.
1113 * @param stdClass $course
1114 * @param stdClass $user
1115 * @param stdClass $coursemodule
1116 * @param stdClass $assign the database assign record
1118 * This prints the submission summary and feedback summary for this student.
1120 function assign_user_complete($course, $user, $coursemodule, $assign) {
1121 global $CFG;
1122 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1124 $context = context_module::instance($coursemodule->id);
1126 $assignment = new assign($context, $coursemodule, $course);
1128 echo $assignment->view_student_summary($user, false);
1132 * Print the grade information for the assignment for this user.
1134 * @param stdClass $course
1135 * @param stdClass $user
1136 * @param stdClass $coursemodule
1137 * @param stdClass $assignment
1139 function assign_user_outline($course, $user, $coursemodule, $assignment) {
1140 global $CFG;
1141 require_once($CFG->libdir.'/gradelib.php');
1142 require_once($CFG->dirroot.'/grade/grading/lib.php');
1144 $gradinginfo = grade_get_grades($course->id,
1145 'mod',
1146 'assign',
1147 $assignment->id,
1148 $user->id);
1150 $gradingitem = $gradinginfo->items[0];
1151 $gradebookgrade = $gradingitem->grades[$user->id];
1153 if (empty($gradebookgrade->str_long_grade)) {
1154 return null;
1156 $result = new stdClass();
1157 $result->info = get_string('outlinegrade', 'assign', $gradebookgrade->str_long_grade);
1158 $result->time = $gradebookgrade->dategraded;
1160 return $result;
1164 * Obtains the automatic completion state for this module based on any conditions
1165 * in assign settings.
1167 * @param object $course Course
1168 * @param object $cm Course-module
1169 * @param int $userid User ID
1170 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
1171 * @return bool True if completed, false if not, $type if conditions not set.
1173 function assign_get_completion_state($course, $cm, $userid, $type) {
1174 global $CFG, $DB;
1175 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1177 $assign = new assign(null, $cm, $course);
1179 // If completion option is enabled, evaluate it and return true/false.
1180 if ($assign->get_instance()->completionsubmit) {
1181 $dbparams = array('assignment'=>$assign->get_instance()->id, 'userid'=>$userid);
1182 $submission = $DB->get_record('assign_submission', $dbparams, '*', IGNORE_MISSING);
1183 return $submission && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1184 } else {
1185 // Completion option is not enabled so just return $type.
1186 return $type;