weekly release 2.8dev
[moodle.git] / mod / assign / lib.php
CommitLineData
a084ac0d 1<?php
bbd0e548
DW
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.
13//
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/>.
16
17/**
e5403f8c 18 * This file contains the moodle hooks for the assign module.
1561a37c 19 *
e5403f8c 20 * It delegates most functions to the assignment class.
bbd0e548
DW
21 *
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
25 */
26defined('MOODLE_INTERNAL') || die();
27
28/**
29 * Adds an assignment instance
30 *
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
35 */
2cffef9f 36function assign_add_instance(stdClass $data, mod_assign_mod_form $form = null) {
bbd0e548
DW
37 global $CFG;
38 require_once($CFG->dirroot . '/mod/assign/locallib.php');
39
40 $assignment = new assign(context_module::instance($data->coursemodule), null, null);
41 return $assignment->add_instance($data, true);
42}
43
44/**
45 * delete an assignment instance
46 * @param int $id
47 * @return bool
48 */
49function 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);
54
55 $assignment = new assign($context, null, null);
56 return $assignment->delete_instance();
57}
58
d38dc52f
RW
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.
1561a37c
DW
63 *
64 * @param stdClass $data the data submitted from the reset course.
65 * @return array
d38dc52f
RW
66 */
67function assign_reset_userdata($data) {
68 global $CFG, $DB;
69 require_once($CFG->dirroot . '/mod/assign/locallib.php');
70
71 $status = array();
72 $params = array('courseid'=>$data->courseid);
73 $sql = "SELECT a.id FROM {assign} a WHERE a.course=:courseid";
74df2951 74 $course = $DB->get_record('course', array('id'=>$data->courseid), '*', MUST_EXIST);
e5403f8c 75 if ($assigns = $DB->get_records_sql($sql, $params)) {
d38dc52f 76 foreach ($assigns as $assign) {
e5403f8c
DW
77 $cm = get_coursemodule_from_instance('assign',
78 $assign->id,
79 $data->courseid,
80 false,
81 MUST_EXIST);
d38dc52f
RW
82 $context = context_module::instance($cm->id);
83 $assignment = new assign($context, $cm, $course);
84 $status = array_merge($status, $assignment->reset_userdata($data));
85 }
86 }
87 return $status;
88}
89
90/**
91 * Removes all grades from gradebook
92 *
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
95 */
96function assign_reset_gradebook($courseid, $type='') {
97 global $CFG, $DB;
98
e5403f8c 99 $params = array('moduletype'=>'assign', 'courseid'=>$courseid);
d38dc52f
RW
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';
103
e5403f8c 104 if ($assignments = $DB->get_records_sql($sql, $params)) {
d38dc52f
RW
105 foreach ($assignments as $assignment) {
106 assign_grade_item_update($assignment, 'reset');
107 }
108 }
109}
110
111/**
112 * Implementation of the function for printing the form elements that control
113 * whether the course reset functionality affects the assignment.
1561a37c 114 * @param moodleform $mform form passed by reference
d38dc52f
RW
115 */
116function assign_reset_course_form_definition(&$mform) {
117 $mform->addElement('header', 'assignheader', get_string('modulenameplural', 'assign'));
e5403f8c
DW
118 $name = get_string('deleteallsubmissions', 'assign');
119 $mform->addElement('advcheckbox', 'reset_assign_submissions', $name);
d38dc52f
RW
120}
121
122/**
123 * Course reset form defaults.
124 * @param object $course
125 * @return array
126 */
127function assign_reset_course_form_defaults($course) {
128 return array('reset_assign_submissions'=>1);
129}
130
bbd0e548
DW
131/**
132 * Update an assignment instance
133 *
134 * This is done by calling the update_instance() method of the assignment type class
135 * @param stdClass $data
1561a37c 136 * @param stdClass $form - unused
bbd0e548
DW
137 * @return object
138 */
dd5d933f 139function assign_update_instance(stdClass $data, $form) {
bbd0e548
DW
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);
145}
146
147/**
148 * Return the list if Moodle features this module supports
149 *
150 * @param string $feature FEATURE_xx constant for requested feature
151 * @return mixed True if module supports feature, null if doesn't know
152 */
153function assign_supports($feature) {
154 switch($feature) {
df211804
DW
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;
179
180 default:
181 return null;
bbd0e548
DW
182 }
183}
184
185/**
186 * Lists all gradable areas for the advanced grading methods gramework
187 *
188 * @return array('string'=>'string') An array with area names as keys and descriptions as values
189 */
190function assign_grading_areas_list() {
191 return array('submissions'=>get_string('submissions', 'assign'));
192}
193
194
195/**
196 * extend an assigment navigation settings
197 *
198 * @param settings_navigation $settings
199 * @param navigation_node $navref
200 * @return void
201 */
202function assign_extend_settings_navigation(settings_navigation $settings, navigation_node $navref) {
b473171a 203 global $PAGE, $DB;
bbd0e548
DW
204
205 $cm = $PAGE->cm;
206 if (!$cm) {
207 return;
208 }
209
210 $context = $cm->context;
211 $course = $PAGE->course;
212
bbd0e548
DW
213 if (!$course) {
214 return;
215 }
216
e5403f8c
DW
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);
223 }
bbd0e548 224
e5403f8c 225 // Link to download all submissions.
4a47008c 226 if (has_any_capability(array('mod/assign:grade', 'mod/assign:viewgrades'), $context)) {
e5403f8c
DW
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);
bbd0e548 229
e5403f8c
DW
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);
232 }
bbd0e548 233
e5403f8c
DW
234 if (has_capability('mod/assign:revealidentities', $context)) {
235 $dbparams = array('id'=>$cm->instance);
236 $assignment = $DB->get_record('assign', $dbparams, 'blindmarking, revealidentities');
b473171a 237
e5403f8c
DW
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);
243 }
244 }
bbd0e548
DW
245}
246
bbd0e548
DW
247/**
248 * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
249 * for the course (see resource).
250 *
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.
253 *
254 * @param stdClass $coursemodule The coursemodule object (record).
e5403f8c
DW
255 * @return cached_cm_info An object on information that the courses
256 * will know about (most noticeably, an icon).
bbd0e548
DW
257 */
258function assign_get_coursemodule_info($coursemodule) {
259 global $CFG, $DB;
260
e5403f8c 261 $dbparams = array('id'=>$coursemodule->instance);
b618f2d9 262 $fields = 'id, name, alwaysshowdescription, allowsubmissionsfromdate, intro, introformat';
e5403f8c 263 if (! $assignment = $DB->get_record('assign', $dbparams, $fields)) {
bbd0e548
DW
264 return false;
265 }
266
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);
273 }
274 }
275 return $result;
276}
277
bbd0e548
DW
278/**
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
283 */
284function assign_page_type_list($pagetype, $parentcontext, $currentcontext) {
539af602 285 $modulepagetype = array(
bbd0e548
DW
286 'mod-assign-*' => get_string('page-mod-assign-x', 'assign'),
287 'mod-assign-view' => get_string('page-mod-assign-view', 'assign'),
288 );
539af602 289 return $modulepagetype;
bbd0e548
DW
290}
291
292/**
293 * Print an overview of all assignments
294 * for the courses.
295 *
296 * @param mixed $courses The list of courses to print the overview for
297 * @param array $htmlarray The array of html to return
298 */
299function assign_print_overview($courses, &$htmlarray) {
300 global $USER, $CFG, $DB;
301
302 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
303 return array();
304 }
305
e5403f8c 306 if (!$assignments = get_all_instances_in_courses('assign', $courses)) {
bbd0e548
DW
307 return;
308 }
309
310 $assignmentids = array();
311
e5403f8c 312 // Do assignment_base::isopen() here without loading the whole thing for speed.
bbd0e548
DW
313 foreach ($assignments as $key => $assignment) {
314 $time = time();
710f1a34 315 $isopen = false;
bbd0e548 316 if ($assignment->duedate) {
9e795179
DW
317 $duedate = false;
318 if ($assignment->cutoffdate) {
319 $duedate = $assignment->cutoffdate;
320 }
321 if ($duedate) {
322 $isopen = ($assignment->allowsubmissionsfromdate <= $time && $time <= $duedate);
323 } else {
324 $isopen = ($assignment->allowsubmissionsfromdate <= $time);
bbd0e548
DW
325 }
326 }
da099b12 327 if ($isopen) {
bbd0e548
DW
328 $assignmentids[] = $assignment->id;
329 }
330 }
331
e5403f8c
DW
332 if (empty($assignmentids)) {
333 // No assignments to look at - we're done.
bbd0e548
DW
334 return true;
335 }
336
d43b3109
DW
337 // Definitely something to print, now include the constants we need.
338 require_once($CFG->dirroot . '/mod/assign/locallib.php');
339
bbd0e548 340 $strduedate = get_string('duedate', 'assign');
9e795179
DW
341 $strcutoffdate = get_string('nosubmissionsacceptedafter', 'assign');
342 $strnolatesubmissions = get_string('nolatesubmissions', 'assign');
343 $strduedateno = get_string('duedateno', 'assign');
bbd0e548
DW
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');
e5403f8c 350 $strreviewed = get_string('reviewed', 'assign');
bbd0e548 351
e5403f8c 352 // We do all possible database work here *outside* of the loop to ensure this scales.
bbd0e548
DW
353 list($sqlassignmentids, $assignmentidparams) = $DB->get_in_or_equal($assignmentids);
354
b8d3aa8f
DW
355 $mysubmissions = null;
356 $unmarkedsubmissions = null;
357
bbd0e548 358 foreach ($assignments as $assignment) {
e5403f8c 359 // Do not show assignments that are not open.
da099b12
DW
360 if (!in_array($assignment->id, $assignmentids)) {
361 continue;
362 }
e5403f8c
DW
363 $dimmedclass = '';
364 if (!$assignment->visible) {
365 $dimmedclass = ' class="dimmed"';
366 }
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>';
bbd0e548 376 if ($assignment->duedate) {
e5403f8c
DW
377 $userdate = userdate($assignment->duedate);
378 $str .= '<div class="info">' . $strduedate . ': ' . $userdate . '</div>';
bbd0e548 379 } else {
e5403f8c 380 $str .= '<div class="info">' . $strduedateno . '</div>';
bbd0e548 381 }
9e795179
DW
382 if ($assignment->cutoffdate) {
383 if ($assignment->cutoffdate == $assignment->duedate) {
e5403f8c 384 $str .= '<div class="info">' . $strnolatesubmissions . '</div>';
9e795179 385 } else {
e5403f8c
DW
386 $userdate = userdate($assignment->cutoffdate);
387 $str .= '<div class="info">' . $strcutoffdate . ': ' . $userdate . '</div>';
9e795179
DW
388 }
389 }
bbd0e548
DW
390 $context = context_module::instance($assignment->coursemodule);
391 if (has_capability('mod/assign:grade', $context)) {
d77731d6 392 if (!isset($unmarkedsubmissions)) {
fc1dac2e
DW
393 $submissionmaxattempt = 'SELECT mxs.userid, MAX(mxs.attemptnumber) AS maxattempt, mxs.assignment
394 FROM {assign_submission} mxs
92d78aac 395 WHERE mxs.assignment ' . $sqlassignmentids . '
fc1dac2e 396 GROUP BY mxs.userid, mxs.assignment';
fc1dac2e 397
d77731d6
EM
398 // Build up and array of unmarked submissions indexed by assignment id/ userid
399 // for use where the user has grading rights on assignment.
92d78aac 400 $dbparams = array_merge($assignmentidparams, array(ASSIGN_SUBMISSION_STATUS_SUBMITTED), $assignmentidparams);
d77731d6
EM
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
fc1dac2e
DW
408 LEFT JOIN ( ' . $submissionmaxattempt . ' ) smx ON
409 smx.userid = s.userid AND
410 smx.assignment = s.id
d77731d6
EM
411 LEFT JOIN {assign_grades} g ON
412 s.userid = g.userid AND
fc1dac2e 413 s.assignment = g.assignment AND
6447021b 414 g.attemptnumber = smx.maxattempt
d77731d6
EM
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
fc1dac2e 420 s.attemptnumber = smx.maxattempt AND
d77731d6
EM
421 s.assignment ' . $sqlassignmentids, $dbparams);
422
423 $unmarkedsubmissions = array();
424 foreach ($rs as $rd) {
425 $unmarkedsubmissions[$rd->assignment][$rd->userid] = $rd->id;
426 }
427 $rs->close();
428 }
429
e5403f8c
DW
430 // Count how many people can submit.
431 $submissions = 0;
bbd0e548
DW
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++;
436 }
437 }
438 }
439
440 if ($submissions) {
e5403f8c
DW
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>';
bbd0e548 447 }
e5403f8c
DW
448 }
449 if (has_capability('mod/assign:submit', $context)) {
d77731d6 450 if (!isset($mysubmissions)) {
fc1dac2e
DW
451
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
92d78aac
DW
455 WHERE mxs.assignment ' . $sqlassignmentids . '
456 AND mxs.userid = ?
fc1dac2e 457 GROUP BY mxs.userid, mxs.assignment';
fc1dac2e 458
d77731d6 459 // Get all user submissions, indexed by assignment id.
92d78aac 460 $dbparams = array_merge($assignmentidparams, array($USER->id, $USER->id, $USER->id), $assignmentidparams);
d77731d6
EM
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
fc1dac2e 469 LEFT JOIN ( ' . $submissionmaxattempt . ' ) smx ON
fc1dac2e 470 smx.assignment = a.id
d77731d6
EM
471 LEFT JOIN {assign_grades} g ON
472 g.assignment = a.id AND
fc1dac2e 473 g.userid = ? AND
6447021b 474 g.attemptnumber = smx.maxattempt
d77731d6 475 LEFT JOIN {assign_submission} s ON
fc1dac2e 476 s.attemptnumber = smx.maxattempt AND
d77731d6
EM
477 s.assignment = a.id AND
478 s.userid = ?
479 WHERE a.id ' . $sqlassignmentids, $dbparams);
480 }
481
bbd0e548
DW
482 $str .= '<div class="details">';
483 $str .= get_string('mysubmission', 'assign');
6447021b
DW
484 $submission = false;
485 if (isset($mysubmissions[$assignment->id])) {
486 $submission = $mysubmissions[$assignment->id];
487 }
488 if (!$submission || !$submission->status || $submission->status == 'draft') {
e5403f8c 489 $str .= $strnotsubmittedyet;
6447021b
DW
490 } else if ($submission->nosubmissions) {
491 $str .= get_string('offline', 'assign');
e5403f8c 492 } else {
bbd0e548
DW
493 $str .= get_string('submissionstatus_' . $submission->status, 'assign');
494 }
6447021b 495 if (!$submission || !$submission->grade || $submission->grade < 0) {
bbd0e548
DW
496 $str .= ', ' . get_string('notgraded', 'assign');
497 } else {
498 $str .= ', ' . get_string('graded', 'assign');
499 }
500 $str .= '</div>';
501 }
e5403f8c 502 $str .= '</div>';
bbd0e548
DW
503 if (empty($htmlarray[$assignment->course]['assign'])) {
504 $htmlarray[$assignment->course]['assign'] = $str;
505 } else {
506 $htmlarray[$assignment->course]['assign'] .= $str;
507 }
508 }
509}
510
511/**
512 * Print recent activity from all assignments in a given course
513 *
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
9682626e 517 * @param int $timestart the time the rendering started
5c7ec9f6 518 * @return bool true if activity was printed, false otherwise.
bbd0e548
DW
519 */
520function assign_print_recent_activity($course, $viewfullnames, $timestart) {
521 global $CFG, $USER, $DB, $OUTPUT;
522
e5403f8c 523 // Do not use log table if possible, it may be huge.
bbd0e548 524
e5403f8c 525 $dbparams = array($timestart, $course->id, 'assign');
5c7ec9f6
AA
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
bbd0e548
DW
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
e5403f8c 536 md.name = ?
5c7ec9f6 537 ORDER BY asb.timemodified ASC", $dbparams)) {
bbd0e548
DW
538 return false;
539 }
540
e5403f8c 541 $modinfo = get_fast_modinfo($course);
bbd0e548
DW
542 $show = array();
543 $grader = array();
544
d6f418cb 545 $showrecentsubmissions = get_config('assign', 'showrecentsubmissions');
cfc81f03 546
e5403f8c 547 foreach ($submissions as $submission) {
bbd0e548
DW
548 if (!array_key_exists($submission->cmid, $modinfo->get_cms())) {
549 continue;
550 }
551 $cm = $modinfo->get_cm($submission->cmid);
552 if (!$cm->uservisible) {
553 continue;
554 }
555 if ($submission->userid == $USER->id) {
556 $show[] = $submission;
557 continue;
558 }
559
560 $context = context_module::instance($submission->cmid);
e5403f8c
DW
561 // The act of submitting of assignment may be considered private -
562 // only graders will see it if specified.
cfc81f03 563 if (empty($showrecentsubmissions)) {
bbd0e548 564 if (!array_key_exists($cm->id, $grader)) {
e5403f8c 565 $grader[$cm->id] = has_capability('moodle/grade:viewall', $context);
bbd0e548
DW
566 }
567 if (!$grader[$cm->id]) {
568 continue;
569 }
570 }
571
572 $groupmode = groups_get_activity_groupmode($cm, $course);
573
e5403f8c
DW
574 if ($groupmode == SEPARATEGROUPS &&
575 !has_capability('moodle/site:accessallgroups', $context)) {
bbd0e548 576 if (isguestuser()) {
e5403f8c 577 // Shortcut - guest user does not belong into any group.
bbd0e548
DW
578 continue;
579 }
580
e5403f8c 581 // This will be slow - show only users that share group with me in this cm.
e19c086c 582 if (!$modinfo->get_groups($cm->groupingid)) {
bbd0e548
DW
583 continue;
584 }
585 $usersgroups = groups_get_all_groups($course->id, $submission->userid, $cm->groupingid);
586 if (is_array($usersgroups)) {
587 $usersgroups = array_keys($usersgroups);
e19c086c 588 $intersect = array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid));
bbd0e548
DW
589 if (empty($intersect)) {
590 continue;
591 }
592 }
593 }
594 $show[] = $submission;
595 }
596
597 if (empty($show)) {
598 return false;
599 }
600
601 echo $OUTPUT->heading(get_string('newsubmissions', 'assign').':', 3);
602
603 foreach ($show as $submission) {
604 $cm = $modinfo->get_cm($submission->cmid);
605 $link = $CFG->wwwroot.'/mod/assign/view.php?id='.$cm->id;
e5403f8c
DW
606 print_recent_activity_note($submission->timemodified,
607 $submission,
608 $cm->name,
609 $link,
610 false,
611 $viewfullnames);
bbd0e548
DW
612 }
613
614 return true;
615}
616
617/**
e5403f8c 618 * Returns all assignments since a given time.
c06b2127 619 *
bbd0e548
DW
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
628 */
e5403f8c
DW
629function assign_get_recent_mod_activity(&$activities,
630 &$index,
631 $timestart,
632 $courseid,
633 $cmid,
634 $userid=0,
635 $groupid=0) {
bbd0e548
DW
636 global $CFG, $COURSE, $USER, $DB;
637
638 if ($COURSE->id == $courseid) {
639 $course = $COURSE;
640 } else {
641 $course = $DB->get_record('course', array('id'=>$courseid));
642 }
643
e5403f8c 644 $modinfo = get_fast_modinfo($course);
bbd0e548
DW
645
646 $cm = $modinfo->get_cm($cmid);
647 $params = array();
648 if ($userid) {
e5403f8c 649 $userselect = 'AND u.id = :userid';
bbd0e548
DW
650 $params['userid'] = $userid;
651 } else {
e5403f8c 652 $userselect = '';
bbd0e548
DW
653 }
654
655 if ($groupid) {
e5403f8c
DW
656 $groupselect = 'AND gm.groupid = :groupid';
657 $groupjoin = 'JOIN {groups_members} gm ON gm.userid=u.id';
bbd0e548
DW
658 $params['groupid'] = $groupid;
659 } else {
e5403f8c
DW
660 $groupselect = '';
661 $groupjoin = '';
bbd0e548
DW
662 }
663
664 $params['cminstance'] = $cm->instance;
665 $params['timestart'] = $timestart;
666
667 $userfields = user_picture::fields('u', null, 'userid');
668
f93fdcef
DW
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
e5403f8c
DW
676 a.id = :cminstance
677 ' . $userselect . ' ' . $groupselect .
678 ' ORDER BY asb.timemodified ASC', $params)) {
bbd0e548
DW
679 return;
680 }
681
682 $groupmode = groups_get_activity_groupmode($cm, $course);
539af602
DW
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);
bbd0e548 687
bbd0e548 688
d6f418cb 689 $showrecentsubmissions = get_config('assign', 'showrecentsubmissions');
bbd0e548 690 $show = array();
e5403f8c 691 foreach ($submissions as $submission) {
bbd0e548
DW
692 if ($submission->userid == $USER->id) {
693 $show[] = $submission;
694 continue;
695 }
e5403f8c
DW
696 // The act of submitting of assignment may be considered private -
697 // only graders will see it if specified.
cfc81f03 698 if (empty($showrecentsubmissions)) {
bbd0e548
DW
699 if (!$grader) {
700 continue;
701 }
702 }
703
704 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
705 if (isguestuser()) {
e5403f8c 706 // Shortcut - guest user does not belong into any group.
bbd0e548
DW
707 continue;
708 }
709
e5403f8c 710 // This will be slow - show only users that share group with me in this cm.
e19c086c 711 if (!$modinfo->get_groups($cm->groupingid)) {
bbd0e548
DW
712 continue;
713 }
e19c086c 714 $usersgroups = groups_get_all_groups($course->id, $submission->userid, $cm->groupingid);
bbd0e548 715 if (is_array($usersgroups)) {
e19c086c
MG
716 $usersgroups = array_keys($usersgroups);
717 $intersect = array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid));
bbd0e548
DW
718 if (empty($intersect)) {
719 continue;
720 }
721 }
722 }
723 $show[] = $submission;
724 }
725
726 if (empty($show)) {
727 return;
728 }
729
730 if ($grader) {
731 require_once($CFG->libdir.'/gradelib.php');
732 $userids = array();
e5403f8c 733 foreach ($show as $id => $submission) {
bbd0e548 734 $userids[] = $submission->userid;
bbd0e548
DW
735 }
736 $grades = grade_get_grades($courseid, 'mod', 'assign', $cm->instance, $userids);
737 }
738
e5403f8c 739 $aname = format_string($cm->name, true);
bbd0e548
DW
740 foreach ($show as $submission) {
741 $activity = new stdClass();
742
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;
751 }
752
753 $userfields = explode(',', user_picture::fields());
754 foreach ($userfields as $userfield) {
755 if ($userfield == 'id') {
e5403f8c
DW
756 // Aliased in SQL above.
757 $activity->user->{$userfield} = $submission->userid;
bbd0e548
DW
758 } else {
759 $activity->user->{$userfield} = $submission->{$userfield};
760 }
761 }
762 $activity->user->fullname = fullname($submission, $viewfullnames);
763
764 $activities[$index++] = $activity;
765 }
766
767 return;
768}
769
770/**
771 * Print recent activity from all assignments in a given course
772 *
773 * This is used by course/recent.php
774 * @param stdClass $activity
775 * @param int $courseid
776 * @param bool $detail
777 * @param array $modnames
778 */
e5403f8c 779function assign_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
bbd0e548
DW
780 global $CFG, $OUTPUT;
781
782 echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
783
e5403f8c 784 echo '<tr><td class="userpicture" valign="top">';
bbd0e548 785 echo $OUTPUT->user_picture($activity->user);
e5403f8c 786 echo '</td><td>';
bbd0e548
DW
787
788 if ($detail) {
789 $modname = $modnames[$activity->type];
790 echo '<div class="title">';
e5403f8c
DW
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>';
bbd0e548
DW
796 echo '</div>';
797 }
798
799 if (isset($activity->grade)) {
800 echo '<div class="grade">';
801 echo get_string('grade').': ';
802 echo $activity->grade;
803 echo '</div>';
804 }
805
806 echo '<div class="user">';
e5403f8c
DW
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);
bbd0e548
DW
809 echo '</div>';
810
e5403f8c 811 echo '</td></tr></table>';
bbd0e548
DW
812}
813
814/**
e5403f8c 815 * Checks if a scale is being used by an assignment.
bbd0e548
DW
816 *
817 * This is used by the backup code to decide whether to back up a scale
9682626e 818 * @param int $assignmentid
bbd0e548
DW
819 * @param int $scaleid
820 * @return boolean True if the scale is used by the assignment
821 */
822function assign_scale_used($assignmentid, $scaleid) {
823 global $DB;
824
825 $return = false;
e5403f8c 826 $rec = $DB->get_record('assign', array('id'=>$assignmentid, 'grade'=>-$scaleid));
bbd0e548
DW
827
828 if (!empty($rec) && !empty($scaleid)) {
829 $return = true;
830 }
831
832 return $return;
833}
834
835/**
836 * Checks if scale is being used by any instance of assignment
837 *
838 * This is used to find out if scale used anywhere
9682626e 839 * @param int $scaleid
bbd0e548
DW
840 * @return boolean True if the scale is used by any assignment
841 */
842function assign_scale_used_anywhere($scaleid) {
843 global $DB;
844
845 if ($scaleid and $DB->record_exists('assign', array('grade'=>-$scaleid))) {
846 return true;
847 } else {
848 return false;
849 }
850}
851
852/**
e5403f8c
DW
853 * List the actions that correspond to a view of this module.
854 * This is used by the participation report.
b2b4ec30
RT
855 *
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.
859 *
bbd0e548
DW
860 * @return array
861 */
862function assign_get_view_actions() {
863 return array('view submission', 'view feedback');
864}
865
866/**
e5403f8c
DW
867 * List the actions that correspond to a post of this module.
868 * This is used by the participation report.
b2b4ec30
RT
869 *
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.
873 *
bbd0e548
DW
874 * @return array
875 */
876function assign_get_post_actions() {
877 return array('upload', 'submit', 'submit for grading');
878}
879
880/**
e5403f8c 881 * Call cron on the assign module.
bbd0e548
DW
882 */
883function assign_cron() {
884 global $CFG;
885
886 require_once($CFG->dirroot . '/mod/assign/locallib.php');
75f87a57
DW
887 assign::cron();
888
bd3b3bba 889 $plugins = core_component::get_plugin_list('assignsubmission');
bbd0e548
DW
890
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();
897 }
898 }
bd3b3bba 899 $plugins = core_component::get_plugin_list('assignfeedback');
bbd0e548
DW
900
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();
907 }
908 }
909}
910
911/**
912 * Returns all other capabilities used by this module.
913 * @return array Array of capability strings
914 */
915function assign_get_extra_capabilities() {
e5403f8c
DW
916 return array('gradereport/grader:view',
917 'moodle/grade:viewall',
918 'moodle/site:viewfullnames',
919 'moodle/site:config');
bbd0e548
DW
920}
921
922/**
e5403f8c 923 * Create grade item for given assignment.
bbd0e548
DW
924 *
925 * @param stdClass $assign record with extra cmidnumber
926 * @param array $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
927 * @return int 0 if ok, error code otherwise
928 */
e5403f8c 929function assign_grade_item_update($assign, $grades=null) {
bbd0e548
DW
930 global $CFG;
931 require_once($CFG->libdir.'/gradelib.php');
932
933 if (!isset($assign->courseid)) {
934 $assign->courseid = $assign->course;
935 }
936
937 $params = array('itemname'=>$assign->name, 'idnumber'=>$assign->cmidnumber);
938
456d7bc7
RT
939 // Check if feedback plugin for gradebook is enabled, if yes then
940 // gradetype = GRADE_TYPE_TEXT else GRADE_TYPE_NONE.
941 $gradefeedbackenabled = false;
942
943 if (isset($assign->gradefeedbackenabled)) {
944 $gradefeedbackenabled = $assign->gradefeedbackenabled;
945 } else if ($assign->grade == 0) { // Grade feedback is needed only when grade == 0.
2507b7e0 946 require_once($CFG->dirroot . '/mod/assign/locallib.php');
456d7bc7
RT
947 $mod = get_coursemodule_from_instance('assign', $assign->id, $assign->courseid);
948 $cm = context_module::instance($mod->id);
949 $assignment = new assign($cm, null, null);
950 $gradefeedbackenabled = $assignment->is_gradebook_feedback_enabled();
951 }
952
bbd0e548
DW
953 if ($assign->grade > 0) {
954 $params['gradetype'] = GRADE_TYPE_VALUE;
955 $params['grademax'] = $assign->grade;
956 $params['grademin'] = 0;
957
958 } else if ($assign->grade < 0) {
959 $params['gradetype'] = GRADE_TYPE_SCALE;
960 $params['scaleid'] = -$assign->grade;
961
456d7bc7
RT
962 } else if ($gradefeedbackenabled) {
963 // $assign->grade == 0 and feedback enabled.
e5403f8c 964 $params['gradetype'] = GRADE_TYPE_TEXT;
456d7bc7
RT
965 } else {
966 // $assign->grade == 0 and no feedback enabled.
967 $params['gradetype'] = GRADE_TYPE_NONE;
bbd0e548
DW
968 }
969
970 if ($grades === 'reset') {
971 $params['reset'] = true;
e5403f8c 972 $grades = null;
bbd0e548
DW
973 }
974
e5403f8c
DW
975 return grade_update('mod/assign',
976 $assign->courseid,
977 'mod',
978 'assign',
979 $assign->id,
980 0,
981 $grades,
982 $params);
bbd0e548
DW
983}
984
985/**
986 * Return grade for given user or all users.
987 *
988 * @param stdClass $assign record of assign with an additional cmidnumber
989 * @param int $userid optional user id, 0 means all users
990 * @return array array of grades, false if none
991 */
992function assign_get_user_grades($assign, $userid=0) {
993 global $CFG;
e5403f8c 994
bbd0e548
DW
995 require_once($CFG->dirroot . '/mod/assign/locallib.php');
996
79e7dfcc
RW
997 $cm = get_coursemodule_from_instance('assign', $assign->id, 0, false, MUST_EXIST);
998 $context = context_module::instance($cm->id);
999 $assignment = new assign($context, null, null);
b11808c7 1000 $assignment->set_instance($assign);
bbd0e548
DW
1001 return $assignment->get_user_grades_for_gradebook($userid);
1002}
1003
1004/**
e5403f8c 1005 * Update activity grades.
bbd0e548
DW
1006 *
1007 * @param stdClass $assign database record
1008 * @param int $userid specific user only, 0 means all
1009 * @param bool $nullifnone - not used
1010 */
1011function assign_update_grades($assign, $userid=0, $nullifnone=true) {
1012 global $CFG;
1013 require_once($CFG->libdir.'/gradelib.php');
1014
1015 if ($assign->grade == 0) {
1016 assign_grade_item_update($assign);
1017
1018 } else if ($grades = assign_get_user_grades($assign, $userid)) {
e5403f8c 1019 foreach ($grades as $k => $v) {
bbd0e548
DW
1020 if ($v->rawgrade == -1) {
1021 $grades[$k]->rawgrade = null;
1022 }
1023 }
1024 assign_grade_item_update($assign, $grades);
1025
1026 } else {
1027 assign_grade_item_update($assign);
1028 }
1029}
1030
1031/**
e5403f8c 1032 * List the file areas that can be browsed.
bbd0e548
DW
1033 *
1034 * @param stdClass $course
1035 * @param stdClass $cm
1036 * @param stdClass $context
1037 * @return array
1038 */
6b8b0b2e 1039function assign_get_file_areas($course, $cm, $context) {
bbd0e548
DW
1040 global $CFG;
1041 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1042 $areas = array();
1043
1044 $assignment = new assign($context, $cm, $course);
1045 foreach ($assignment->get_submission_plugins() as $plugin) {
1046 if ($plugin->is_visible()) {
1047 $pluginareas = $plugin->get_file_areas();
1048
1049 if ($pluginareas) {
1050 $areas = array_merge($areas, $pluginareas);
1051 }
1052 }
1053 }
1054 foreach ($assignment->get_feedback_plugins() as $plugin) {
1055 if ($plugin->is_visible()) {
1056 $pluginareas = $plugin->get_file_areas();
1057
1058 if ($pluginareas) {
1059 $areas = array_merge($areas, $pluginareas);
1060 }
1061 }
1062 }
1063
1064 return $areas;
1065}
1066
1067/**
1068 * File browsing support for assign module.
1069 *
1070 * @param file_browser $browser
1071 * @param object $areas
1072 * @param object $course
1073 * @param object $cm
1074 * @param object $context
1075 * @param string $filearea
1076 * @param int $itemid
1077 * @param string $filepath
1078 * @param string $filename
1079 * @return object file_info instance or null if not found
1080 */
e5403f8c
DW
1081function assign_get_file_info($browser,
1082 $areas,
1083 $course,
1084 $cm,
1085 $context,
1086 $filearea,
1087 $itemid,
1088 $filepath,
1089 $filename) {
bbd0e548
DW
1090 global $CFG;
1091 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1092
1093 if ($context->contextlevel != CONTEXT_MODULE) {
1094 return null;
1095 }
1096
1097 $fs = get_file_storage();
1098 $filepath = is_null($filepath) ? '/' : $filepath;
1099 $filename = is_null($filename) ? '.' : $filename;
1100
e5403f8c 1101 // Need to find the plugin this belongs to.
bbd0e548
DW
1102 $assignment = new assign($context, $cm, $course);
1103 $pluginowner = null;
1104 foreach ($assignment->get_submission_plugins() as $plugin) {
1105 if ($plugin->is_visible()) {
1106 $pluginareas = $plugin->get_file_areas();
1107
1108 if (array_key_exists($filearea, $pluginareas)) {
1109 $pluginowner = $plugin;
1110 break;
1111 }
1112 }
1113 }
1114 if (!$pluginowner) {
1115 foreach ($assignment->get_feedback_plugins() as $plugin) {
1116 if ($plugin->is_visible()) {
1117 $pluginareas = $plugin->get_file_areas();
1118
1119 if (array_key_exists($filearea, $pluginareas)) {
1120 $pluginowner = $plugin;
1121 break;
1122 }
1123 }
1124 }
1125 }
1126
1127 if (!$pluginowner) {
1128 return null;
1129 }
1130
1131 $result = $pluginowner->get_file_info($browser, $filearea, $itemid, $filepath, $filename);
1132 return $result;
1133}
1134
1135/**
e5403f8c 1136 * Prints the complete info about a user's interaction with an assignment.
bbd0e548
DW
1137 *
1138 * @param stdClass $course
1139 * @param stdClass $user
1140 * @param stdClass $coursemodule
1141 * @param stdClass $assign the database assign record
1142 *
e5403f8c 1143 * This prints the submission summary and feedback summary for this student.
bbd0e548
DW
1144 */
1145function assign_user_complete($course, $user, $coursemodule, $assign) {
1146 global $CFG;
1147 require_once($CFG->dirroot . '/mod/assign/locallib.php');
e5403f8c 1148
bbd0e548
DW
1149 $context = context_module::instance($coursemodule->id);
1150
1151 $assignment = new assign($context, $coursemodule, $course);
1152
1153 echo $assignment->view_student_summary($user, false);
1154}
1155
1156/**
e5403f8c 1157 * Print the grade information for the assignment for this user.
9682626e 1158 *
bbd0e548
DW
1159 * @param stdClass $course
1160 * @param stdClass $user
1161 * @param stdClass $coursemodule
1162 * @param stdClass $assignment
1163 */
1164function assign_user_outline($course, $user, $coursemodule, $assignment) {
1165 global $CFG;
1166 require_once($CFG->libdir.'/gradelib.php');
1167 require_once($CFG->dirroot.'/grade/grading/lib.php');
1168
1169 $gradinginfo = grade_get_grades($course->id,
1170 'mod',
1171 'assign',
1172 $assignment->id,
1173 $user->id);
1174
1175 $gradingitem = $gradinginfo->items[0];
1176 $gradebookgrade = $gradingitem->grades[$user->id];
1177
f6aa750e 1178 if (empty($gradebookgrade->str_long_grade)) {
bbd0e548
DW
1179 return null;
1180 }
1181 $result = new stdClass();
f6aa750e 1182 $result->info = get_string('outlinegrade', 'assign', $gradebookgrade->str_long_grade);
bbd0e548
DW
1183 $result->time = $gradebookgrade->dategraded;
1184
1185 return $result;
1186}
79ed4d84
DW
1187
1188/**
1189 * Obtains the automatic completion state for this module based on any conditions
1190 * in assign settings.
1191 *
1192 * @param object $course Course
1193 * @param object $cm Course-module
1194 * @param int $userid User ID
1195 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
1196 * @return bool True if completed, false if not, $type if conditions not set.
1197 */
3a66d425 1198function assign_get_completion_state($course, $cm, $userid, $type) {
e5403f8c 1199 global $CFG, $DB;
79ed4d84
DW
1200 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1201
1202 $assign = new assign(null, $cm, $course);
1203
3a66d425
DP
1204 // If completion option is enabled, evaluate it and return true/false.
1205 if ($assign->get_instance()->completionsubmit) {
e5403f8c
DW
1206 $dbparams = array('assignment'=>$assign->get_instance()->id, 'userid'=>$userid);
1207 $submission = $DB->get_record('assign_submission', $dbparams, '*', IGNORE_MISSING);
79ed4d84
DW
1208 return $submission && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1209 } else {
3a66d425 1210 // Completion option is not enabled so just return $type.
79ed4d84
DW
1211 return $type;
1212 }
1213}