MDL-35127 Assignment - declare the variables in the outer scope (for readability)
[moodle.git] / mod / assign / lib.php
CommitLineData
bbd0e548
DW
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.
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
DW
18 * This file contains the moodle hooks for the assign module.
19 * It delegates most functions to the assignment class.
bbd0e548
DW
20 *
21 * @package mod_assign
22 * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
25defined('MOODLE_INTERNAL') || die();
26
27/**
28 * Adds an assignment instance
29 *
30 * This is done by calling the add_instance() method of the assignment type class
31 * @param stdClass $data
32 * @param mod_assign_mod_form $form
33 * @return int The instance id of the new assignment
34 */
2cffef9f 35function assign_add_instance(stdClass $data, mod_assign_mod_form $form = null) {
bbd0e548
DW
36 global $CFG;
37 require_once($CFG->dirroot . '/mod/assign/locallib.php');
38
39 $assignment = new assign(context_module::instance($data->coursemodule), null, null);
40 return $assignment->add_instance($data, true);
41}
42
43/**
44 * delete an assignment instance
45 * @param int $id
46 * @return bool
47 */
48function assign_delete_instance($id) {
49 global $CFG;
50 require_once($CFG->dirroot . '/mod/assign/locallib.php');
51 $cm = get_coursemodule_from_instance('assign', $id, 0, false, MUST_EXIST);
52 $context = context_module::instance($cm->id);
53
54 $assignment = new assign($context, null, null);
55 return $assignment->delete_instance();
56}
57
d38dc52f
RW
58/**
59 * This function is used by the reset_course_userdata function in moodlelib.
60 * This function will remove all assignment submissions and feedbacks in the database
61 * and clean up any related data.
62 * @param $data the data submitted from the reset course.
63 * @return array status array
64 */
65function assign_reset_userdata($data) {
66 global $CFG, $DB;
67 require_once($CFG->dirroot . '/mod/assign/locallib.php');
68
69 $status = array();
70 $params = array('courseid'=>$data->courseid);
71 $sql = "SELECT a.id FROM {assign} a WHERE a.course=:courseid";
e5403f8c
DW
72 $course = $DB->get_record('course', array('id'=>$data->courseid), '*', MUST_EXIST);
73 if ($assigns = $DB->get_records_sql($sql, $params)) {
d38dc52f 74 foreach ($assigns as $assign) {
e5403f8c
DW
75 $cm = get_coursemodule_from_instance('assign',
76 $assign->id,
77 $data->courseid,
78 false,
79 MUST_EXIST);
d38dc52f
RW
80 $context = context_module::instance($cm->id);
81 $assignment = new assign($context, $cm, $course);
82 $status = array_merge($status, $assignment->reset_userdata($data));
83 }
84 }
85 return $status;
86}
87
88/**
89 * Removes all grades from gradebook
90 *
91 * @param int $courseid The ID of the course to reset
92 * @param string $type Optional type of assignment to limit the reset to a particular assignment type
93 */
94function assign_reset_gradebook($courseid, $type='') {
95 global $CFG, $DB;
96
e5403f8c 97 $params = array('moduletype'=>'assign', 'courseid'=>$courseid);
d38dc52f
RW
98 $sql = 'SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
99 FROM {assign} a, {course_modules} cm, {modules} m
100 WHERE m.name=:moduletype AND m.id=cm.module AND cm.instance=a.id AND a.course=:courseid';
101
e5403f8c 102 if ($assignments = $DB->get_records_sql($sql, $params)) {
d38dc52f
RW
103 foreach ($assignments as $assignment) {
104 assign_grade_item_update($assignment, 'reset');
105 }
106 }
107}
108
109/**
110 * Implementation of the function for printing the form elements that control
111 * whether the course reset functionality affects the assignment.
112 * @param $mform form passed by reference
113 */
114function assign_reset_course_form_definition(&$mform) {
115 $mform->addElement('header', 'assignheader', get_string('modulenameplural', 'assign'));
e5403f8c
DW
116 $name = get_string('deleteallsubmissions', 'assign');
117 $mform->addElement('advcheckbox', 'reset_assign_submissions', $name);
d38dc52f
RW
118}
119
120/**
121 * Course reset form defaults.
122 * @param object $course
123 * @return array
124 */
125function assign_reset_course_form_defaults($course) {
126 return array('reset_assign_submissions'=>1);
127}
128
bbd0e548
DW
129/**
130 * Update an assignment instance
131 *
132 * This is done by calling the update_instance() method of the assignment type class
133 * @param stdClass $data
134 * @param mod_assign_mod_form $form
135 * @return object
136 */
137function assign_update_instance(stdClass $data, mod_assign_mod_form $form) {
138 global $CFG;
139 require_once($CFG->dirroot . '/mod/assign/locallib.php');
140 $context = context_module::instance($data->coursemodule);
141 $assignment = new assign($context, null, null);
142 return $assignment->update_instance($data);
143}
144
145/**
146 * Return the list if Moodle features this module supports
147 *
148 * @param string $feature FEATURE_xx constant for requested feature
149 * @return mixed True if module supports feature, null if doesn't know
150 */
151function assign_supports($feature) {
152 switch($feature) {
153 case FEATURE_GROUPS: return true;
154 case FEATURE_GROUPINGS: return true;
155 case FEATURE_GROUPMEMBERSONLY: return true;
156 case FEATURE_MOD_INTRO: return true;
157 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
79ed4d84 158 case FEATURE_COMPLETION_HAS_RULES: return true;
bbd0e548
DW
159 case FEATURE_GRADE_HAS_GRADE: return true;
160 case FEATURE_GRADE_OUTCOMES: return true;
161 case FEATURE_BACKUP_MOODLE2: return true;
162 case FEATURE_SHOW_DESCRIPTION: return true;
163 case FEATURE_ADVANCED_GRADING: return true;
50da4ddd 164 case FEATURE_PLAGIARISM: return true;
bbd0e548
DW
165
166 default: return null;
167 }
168}
169
170/**
171 * Lists all gradable areas for the advanced grading methods gramework
172 *
173 * @return array('string'=>'string') An array with area names as keys and descriptions as values
174 */
175function assign_grading_areas_list() {
176 return array('submissions'=>get_string('submissions', 'assign'));
177}
178
179
180/**
181 * extend an assigment navigation settings
182 *
183 * @param settings_navigation $settings
184 * @param navigation_node $navref
185 * @return void
186 */
187function assign_extend_settings_navigation(settings_navigation $settings, navigation_node $navref) {
b473171a 188 global $PAGE, $DB;
bbd0e548
DW
189
190 $cm = $PAGE->cm;
191 if (!$cm) {
192 return;
193 }
194
195 $context = $cm->context;
196 $course = $PAGE->course;
197
bbd0e548
DW
198 if (!$course) {
199 return;
200 }
201
e5403f8c
DW
202 // Link to gradebook.
203 if (has_capability('gradereport/grader:view', $cm->context) &&
204 has_capability('moodle/grade:viewall', $cm->context)) {
205 $link = new moodle_url('/grade/report/grader/index.php', array('id' => $course->id));
206 $linkname = get_string('viewgradebook', 'assign');
207 $node = $navref->add($linkname, $link, navigation_node::TYPE_SETTING);
208 }
bbd0e548 209
e5403f8c
DW
210 // Link to download all submissions.
211 if (has_capability('mod/assign:grade', $context)) {
212 $link = new moodle_url('/mod/assign/view.php', array('id' => $cm->id, 'action'=>'grading'));
213 $node = $navref->add(get_string('viewgrading', 'assign'), $link, navigation_node::TYPE_SETTING);
bbd0e548 214
e5403f8c
DW
215 $link = new moodle_url('/mod/assign/view.php', array('id' => $cm->id, 'action'=>'downloadall'));
216 $node = $navref->add(get_string('downloadall', 'assign'), $link, navigation_node::TYPE_SETTING);
217 }
bbd0e548 218
e5403f8c
DW
219 if (has_capability('mod/assign:revealidentities', $context)) {
220 $dbparams = array('id'=>$cm->instance);
221 $assignment = $DB->get_record('assign', $dbparams, 'blindmarking, revealidentities');
b473171a 222
e5403f8c
DW
223 if ($assignment && $assignment->blindmarking && !$assignment->revealidentities) {
224 $urlparams = array('id' => $cm->id, 'action'=>'revealidentities');
225 $url = new moodle_url('/mod/assign/view.php', $urlparams);
226 $linkname = get_string('revealidentities', 'assign');
227 $node = $navref->add($linkname, $url, navigation_node::TYPE_SETTING);
228 }
229 }
bbd0e548
DW
230}
231
bbd0e548
DW
232/**
233 * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
234 * for the course (see resource).
235 *
236 * Given a course_module object, this function returns any "extra" information that may be needed
237 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
238 *
239 * @param stdClass $coursemodule The coursemodule object (record).
e5403f8c
DW
240 * @return cached_cm_info An object on information that the courses
241 * will know about (most noticeably, an icon).
bbd0e548
DW
242 */
243function assign_get_coursemodule_info($coursemodule) {
244 global $CFG, $DB;
245
e5403f8c
DW
246 $dbparams = array('id'=>$coursemodule->instance);
247 $fields = 'id, name, alwaysshowdescription, allowsubmissionsfromdate, intro, introformat';
248 if (! $assignment = $DB->get_record('assign', $dbparams, $fields)) {
bbd0e548
DW
249 return false;
250 }
251
252 $result = new cached_cm_info();
253 $result->name = $assignment->name;
254 if ($coursemodule->showdescription) {
255 if ($assignment->alwaysshowdescription || time() > $assignment->allowsubmissionsfromdate) {
256 // Convert intro to html. Do not filter cached version, filters run at display time.
257 $result->content = format_module_intro('assign', $assignment, $coursemodule->id, false);
258 }
259 }
260 return $result;
261}
262
bbd0e548
DW
263/**
264 * Return a list of page types
265 * @param string $pagetype current page type
266 * @param stdClass $parentcontext Block's parent context
267 * @param stdClass $currentcontext Current context of block
268 */
269function assign_page_type_list($pagetype, $parentcontext, $currentcontext) {
270 $module_pagetype = array(
271 'mod-assign-*' => get_string('page-mod-assign-x', 'assign'),
272 'mod-assign-view' => get_string('page-mod-assign-view', 'assign'),
273 );
274 return $module_pagetype;
275}
276
277/**
278 * Print an overview of all assignments
279 * for the courses.
280 *
281 * @param mixed $courses The list of courses to print the overview for
282 * @param array $htmlarray The array of html to return
283 */
284function assign_print_overview($courses, &$htmlarray) {
285 global $USER, $CFG, $DB;
286
287 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
288 return array();
289 }
290
e5403f8c 291 if (!$assignments = get_all_instances_in_courses('assign', $courses)) {
bbd0e548
DW
292 return;
293 }
294
295 $assignmentids = array();
296
e5403f8c 297 // Do assignment_base::isopen() here without loading the whole thing for speed.
bbd0e548
DW
298 foreach ($assignments as $key => $assignment) {
299 $time = time();
710f1a34 300 $isopen = false;
bbd0e548 301 if ($assignment->duedate) {
9e795179
DW
302 $duedate = false;
303 if ($assignment->cutoffdate) {
304 $duedate = $assignment->cutoffdate;
305 }
306 if ($duedate) {
307 $isopen = ($assignment->allowsubmissionsfromdate <= $time && $time <= $duedate);
308 } else {
309 $isopen = ($assignment->allowsubmissionsfromdate <= $time);
bbd0e548
DW
310 }
311 }
da099b12 312 if ($isopen) {
bbd0e548
DW
313 $assignmentids[] = $assignment->id;
314 }
315 }
316
e5403f8c
DW
317 if (empty($assignmentids)) {
318 // No assignments to look at - we're done.
bbd0e548
DW
319 return true;
320 }
321
d43b3109
DW
322 // Definitely something to print, now include the constants we need.
323 require_once($CFG->dirroot . '/mod/assign/locallib.php');
324
bbd0e548 325 $strduedate = get_string('duedate', 'assign');
9e795179
DW
326 $strcutoffdate = get_string('nosubmissionsacceptedafter', 'assign');
327 $strnolatesubmissions = get_string('nolatesubmissions', 'assign');
328 $strduedateno = get_string('duedateno', 'assign');
bbd0e548
DW
329 $strduedateno = get_string('duedateno', 'assign');
330 $strgraded = get_string('graded', 'assign');
331 $strnotgradedyet = get_string('notgradedyet', 'assign');
332 $strnotsubmittedyet = get_string('notsubmittedyet', 'assign');
333 $strsubmitted = get_string('submitted', 'assign');
334 $strassignment = get_string('modulename', 'assign');
e5403f8c 335 $strreviewed = get_string('reviewed', 'assign');
bbd0e548 336
e5403f8c 337 // We do all possible database work here *outside* of the loop to ensure this scales.
bbd0e548
DW
338 list($sqlassignmentids, $assignmentidparams) = $DB->get_in_or_equal($assignmentids);
339
b8d3aa8f
DW
340 $mysubmissions = null;
341 $unmarkedsubmissions = null;
342
bbd0e548 343 foreach ($assignments as $assignment) {
e5403f8c 344 // Do not show assignments that are not open.
da099b12
DW
345 if (!in_array($assignment->id, $assignmentids)) {
346 continue;
347 }
e5403f8c
DW
348 $dimmedclass = '';
349 if (!$assignment->visible) {
350 $dimmedclass = ' class="dimmed"';
351 }
352 $href = $CFG->wwwroot . '/mod/assign/view.php?id=' . $assignment->coursemodule;
353 $str = '<div class="assign overview">' .
354 '<div class="name">' .
355 $strassignment . ': '.
356 '<a ' . $dimmedclass .
357 'title="' . $strassignment . '" ' .
358 'href="' . $href . '">' .
359 format_string($assignment->name) .
360 '</a></div>';
bbd0e548 361 if ($assignment->duedate) {
e5403f8c
DW
362 $userdate = userdate($assignment->duedate);
363 $str .= '<div class="info">' . $strduedate . ': ' . $userdate . '</div>';
bbd0e548 364 } else {
e5403f8c 365 $str .= '<div class="info">' . $strduedateno . '</div>';
bbd0e548 366 }
9e795179
DW
367 if ($assignment->cutoffdate) {
368 if ($assignment->cutoffdate == $assignment->duedate) {
e5403f8c 369 $str .= '<div class="info">' . $strnolatesubmissions . '</div>';
9e795179 370 } else {
e5403f8c
DW
371 $userdate = userdate($assignment->cutoffdate);
372 $str .= '<div class="info">' . $strcutoffdate . ': ' . $userdate . '</div>';
9e795179
DW
373 }
374 }
bbd0e548
DW
375 $context = context_module::instance($assignment->coursemodule);
376 if (has_capability('mod/assign:grade', $context)) {
d77731d6
EM
377 if (!isset($unmarkedsubmissions)) {
378 // Build up and array of unmarked submissions indexed by assignment id/ userid
379 // for use where the user has grading rights on assignment.
380 $dbparams = array_merge(array(ASSIGN_SUBMISSION_STATUS_SUBMITTED), $assignmentidparams);
381 $rs = $DB->get_recordset_sql('SELECT
382 s.assignment as assignment,
383 s.userid as userid,
384 s.id as id,
385 s.status as status,
386 g.timemodified as timegraded
387 FROM {assign_submission} s
388 LEFT JOIN {assign_grades} g ON
389 s.userid = g.userid AND
390 s.assignment = g.assignment
391 WHERE
392 ( g.timemodified is NULL OR
393 s.timemodified > g.timemodified ) AND
394 s.timemodified IS NOT NULL AND
395 s.status = ? AND
396 s.assignment ' . $sqlassignmentids, $dbparams);
397
398 $unmarkedsubmissions = array();
399 foreach ($rs as $rd) {
400 $unmarkedsubmissions[$rd->assignment][$rd->userid] = $rd->id;
401 }
402 $rs->close();
403 }
404
e5403f8c
DW
405 // Count how many people can submit.
406 $submissions = 0;
bbd0e548
DW
407 if ($students = get_enrolled_users($context, 'mod/assign:view', 0, 'u.id')) {
408 foreach ($students as $student) {
409 if (isset($unmarkedsubmissions[$assignment->id][$student->id])) {
410 $submissions++;
411 }
412 }
413 }
414
415 if ($submissions) {
e5403f8c
DW
416 $urlparams = array('id'=>$assignment->coursemodule, 'action'=>'grading');
417 $url = new moodle_url('/mod/assign/view.php', $urlparams);
418 $str .= '<div class="details">' .
419 '<a href="' . $url . '">' .
420 get_string('submissionsnotgraded', 'assign', $submissions) .
421 '</a></div>';
bbd0e548 422 }
e5403f8c
DW
423 }
424 if (has_capability('mod/assign:submit', $context)) {
d77731d6
EM
425 if (!isset($mysubmissions)) {
426 // Get all user submissions, indexed by assignment id.
427 $dbparams = array_merge(array($USER->id, $USER->id), $assignmentidparams);
428 $mysubmissions = $DB->get_records_sql('SELECT
429 a.id AS assignment,
430 a.nosubmissions AS nosubmissions,
431 g.timemodified AS timemarked,
432 g.grader AS grader,
433 g.grade AS grade,
434 s.status AS status
435 FROM {assign} a
436 LEFT JOIN {assign_grades} g ON
437 g.assignment = a.id AND
438 g.userid = ?
439 LEFT JOIN {assign_submission} s ON
440 s.assignment = a.id AND
441 s.userid = ?
442 WHERE a.id ' . $sqlassignmentids, $dbparams);
443 }
444
bbd0e548
DW
445 $str .= '<div class="details">';
446 $str .= get_string('mysubmission', 'assign');
447 $submission = $mysubmissions[$assignment->id];
93c18e73 448 if ($submission->nosubmissions) {
e5403f8c
DW
449 $str .= get_string('offline', 'assign');
450 } else if (!$submission->status || $submission->status == 'draft') {
451 $str .= $strnotsubmittedyet;
452 } else {
bbd0e548
DW
453 $str .= get_string('submissionstatus_' . $submission->status, 'assign');
454 }
455 if (!$submission->grade || $submission->grade < 0) {
456 $str .= ', ' . get_string('notgraded', 'assign');
457 } else {
458 $str .= ', ' . get_string('graded', 'assign');
459 }
460 $str .= '</div>';
461 }
e5403f8c 462 $str .= '</div>';
bbd0e548
DW
463 if (empty($htmlarray[$assignment->course]['assign'])) {
464 $htmlarray[$assignment->course]['assign'] = $str;
465 } else {
466 $htmlarray[$assignment->course]['assign'] .= $str;
467 }
468 }
469}
470
471/**
472 * Print recent activity from all assignments in a given course
473 *
474 * This is used by the recent activity block
475 * @param mixed $course the course to print activity for
476 * @param bool $viewfullnames boolean to determine whether to show full names or not
9682626e 477 * @param int $timestart the time the rendering started
bbd0e548
DW
478 */
479function assign_print_recent_activity($course, $viewfullnames, $timestart) {
480 global $CFG, $USER, $DB, $OUTPUT;
481
e5403f8c 482 // Do not use log table if possible, it may be huge.
bbd0e548 483
e5403f8c
DW
484 $dbparams = array($timestart, $course->id, 'assign');
485 if (!$submissions = $DB->get_records_sql('SELECT asb.id, asb.timemodified, cm.id AS cmid, asb.userid,
bbd0e548
DW
486 u.firstname, u.lastname, u.email, u.picture
487 FROM {assign_submission} asb
488 JOIN {assign} a ON a.id = asb.assignment
489 JOIN {course_modules} cm ON cm.instance = a.id
490 JOIN {modules} md ON md.id = cm.module
491 JOIN {user} u ON u.id = asb.userid
492 WHERE asb.timemodified > ? AND
493 a.course = ? AND
e5403f8c
DW
494 md.name = ?
495 ORDER BY asb.timemodified ASC', $dbparams)) {
bbd0e548
DW
496 return false;
497 }
498
e5403f8c 499 $modinfo = get_fast_modinfo($course);
bbd0e548
DW
500 $show = array();
501 $grader = array();
502
cfc81f03
DW
503 $showrecentsubmissions = get_config('mod_assign', 'showrecentsubmissions');
504
e5403f8c 505 foreach ($submissions as $submission) {
bbd0e548
DW
506 if (!array_key_exists($submission->cmid, $modinfo->get_cms())) {
507 continue;
508 }
509 $cm = $modinfo->get_cm($submission->cmid);
510 if (!$cm->uservisible) {
511 continue;
512 }
513 if ($submission->userid == $USER->id) {
514 $show[] = $submission;
515 continue;
516 }
517
518 $context = context_module::instance($submission->cmid);
e5403f8c
DW
519 // The act of submitting of assignment may be considered private -
520 // only graders will see it if specified.
cfc81f03 521 if (empty($showrecentsubmissions)) {
bbd0e548 522 if (!array_key_exists($cm->id, $grader)) {
e5403f8c 523 $grader[$cm->id] = has_capability('moodle/grade:viewall', $context);
bbd0e548
DW
524 }
525 if (!$grader[$cm->id]) {
526 continue;
527 }
528 }
529
530 $groupmode = groups_get_activity_groupmode($cm, $course);
531
e5403f8c
DW
532 if ($groupmode == SEPARATEGROUPS &&
533 !has_capability('moodle/site:accessallgroups', $context)) {
bbd0e548 534 if (isguestuser()) {
e5403f8c 535 // Shortcut - guest user does not belong into any group.
bbd0e548
DW
536 continue;
537 }
538
539 if (is_null($modinfo->get_groups())) {
e5403f8c
DW
540 // Load all my groups and cache it in modinfo.
541 $modinfo->groups = groups_get_user_groups($course->id);
bbd0e548
DW
542 }
543
e5403f8c 544 // This will be slow - show only users that share group with me in this cm.
bbd0e548
DW
545 if (empty($modinfo->groups[$cm->id])) {
546 continue;
547 }
548 $usersgroups = groups_get_all_groups($course->id, $submission->userid, $cm->groupingid);
549 if (is_array($usersgroups)) {
550 $usersgroups = array_keys($usersgroups);
551 $intersect = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
552 if (empty($intersect)) {
553 continue;
554 }
555 }
556 }
557 $show[] = $submission;
558 }
559
560 if (empty($show)) {
561 return false;
562 }
563
564 echo $OUTPUT->heading(get_string('newsubmissions', 'assign').':', 3);
565
566 foreach ($show as $submission) {
567 $cm = $modinfo->get_cm($submission->cmid);
568 $link = $CFG->wwwroot.'/mod/assign/view.php?id='.$cm->id;
e5403f8c
DW
569 print_recent_activity_note($submission->timemodified,
570 $submission,
571 $cm->name,
572 $link,
573 false,
574 $viewfullnames);
bbd0e548
DW
575 }
576
577 return true;
578}
579
580/**
e5403f8c 581 * Returns all assignments since a given time.
c06b2127 582 *
bbd0e548
DW
583 * @param array $activities The activity information is returned in this array
584 * @param int $index The current index in the activities array
585 * @param int $timestart The earliest activity to show
586 * @param int $courseid Limit the search to this course
587 * @param int $cmid The course module id
588 * @param int $userid Optional user id
589 * @param int $groupid Optional group id
590 * @return void
591 */
e5403f8c
DW
592function assign_get_recent_mod_activity(&$activities,
593 &$index,
594 $timestart,
595 $courseid,
596 $cmid,
597 $userid=0,
598 $groupid=0) {
bbd0e548
DW
599 global $CFG, $COURSE, $USER, $DB;
600
601 if ($COURSE->id == $courseid) {
602 $course = $COURSE;
603 } else {
604 $course = $DB->get_record('course', array('id'=>$courseid));
605 }
606
e5403f8c 607 $modinfo = get_fast_modinfo($course);
bbd0e548
DW
608
609 $cm = $modinfo->get_cm($cmid);
610 $params = array();
611 if ($userid) {
e5403f8c 612 $userselect = 'AND u.id = :userid';
bbd0e548
DW
613 $params['userid'] = $userid;
614 } else {
e5403f8c 615 $userselect = '';
bbd0e548
DW
616 }
617
618 if ($groupid) {
e5403f8c
DW
619 $groupselect = 'AND gm.groupid = :groupid';
620 $groupjoin = 'JOIN {groups_members} gm ON gm.userid=u.id';
bbd0e548
DW
621 $params['groupid'] = $groupid;
622 } else {
e5403f8c
DW
623 $groupselect = '';
624 $groupjoin = '';
bbd0e548
DW
625 }
626
627 $params['cminstance'] = $cm->instance;
628 $params['timestart'] = $timestart;
629
630 $userfields = user_picture::fields('u', null, 'userid');
631
f93fdcef
DW
632 if (!$submissions = $DB->get_records_sql('SELECT asb.id, asb.timemodified, ' .
633 $userfields .
634 ' FROM {assign_submission} asb
635 JOIN {assign} a ON a.id = asb.assignment
636 JOIN {user} u ON u.id = asb.userid ' .
637 $groupjoin .
638 ' WHERE asb.timemodified > :timestart AND
e5403f8c
DW
639 a.id = :cminstance
640 ' . $userselect . ' ' . $groupselect .
641 ' ORDER BY asb.timemodified ASC', $params)) {
bbd0e548
DW
642 return;
643 }
644
645 $groupmode = groups_get_activity_groupmode($cm, $course);
646 $cm_context = context_module::instance($cm->id);
647 $grader = has_capability('moodle/grade:viewall', $cm_context);
648 $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
649 $viewfullnames = has_capability('moodle/site:viewfullnames', $cm_context);
650
651 if (is_null($modinfo->get_groups())) {
e5403f8c
DW
652 // Load all my groups and cache it in modinfo.
653 $modinfo->groups = groups_get_user_groups($course->id);
bbd0e548
DW
654 }
655
cfc81f03 656 $showrecentsubmissions = get_config('mod_assign', 'showrecentsubmissions');
bbd0e548
DW
657 $show = array();
658 $usersgroups = groups_get_all_groups($course->id, $USER->id, $cm->groupingid);
659 if (is_array($usersgroups)) {
660 $usersgroups = array_keys($usersgroups);
661 }
e5403f8c 662 foreach ($submissions as $submission) {
bbd0e548
DW
663 if ($submission->userid == $USER->id) {
664 $show[] = $submission;
665 continue;
666 }
e5403f8c
DW
667 // The act of submitting of assignment may be considered private -
668 // only graders will see it if specified.
cfc81f03 669 if (empty($showrecentsubmissions)) {
bbd0e548
DW
670 if (!$grader) {
671 continue;
672 }
673 }
674
675 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
676 if (isguestuser()) {
e5403f8c 677 // Shortcut - guest user does not belong into any group.
bbd0e548
DW
678 continue;
679 }
680
e5403f8c 681 // This will be slow - show only users that share group with me in this cm.
bbd0e548
DW
682 if (empty($modinfo->groups[$cm->id])) {
683 continue;
684 }
685 if (is_array($usersgroups)) {
686 $intersect = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
687 if (empty($intersect)) {
688 continue;
689 }
690 }
691 }
692 $show[] = $submission;
693 }
694
695 if (empty($show)) {
696 return;
697 }
698
699 if ($grader) {
700 require_once($CFG->libdir.'/gradelib.php');
701 $userids = array();
e5403f8c 702 foreach ($show as $id => $submission) {
bbd0e548 703 $userids[] = $submission->userid;
bbd0e548
DW
704 }
705 $grades = grade_get_grades($courseid, 'mod', 'assign', $cm->instance, $userids);
706 }
707
e5403f8c 708 $aname = format_string($cm->name, true);
bbd0e548
DW
709 foreach ($show as $submission) {
710 $activity = new stdClass();
711
712 $activity->type = 'assign';
713 $activity->cmid = $cm->id;
714 $activity->name = $aname;
715 $activity->sectionnum = $cm->sectionnum;
716 $activity->timestamp = $submission->timemodified;
717 $activity->user = new stdClass();
718 if ($grader) {
719 $activity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
720 }
721
722 $userfields = explode(',', user_picture::fields());
723 foreach ($userfields as $userfield) {
724 if ($userfield == 'id') {
e5403f8c
DW
725 // Aliased in SQL above.
726 $activity->user->{$userfield} = $submission->userid;
bbd0e548
DW
727 } else {
728 $activity->user->{$userfield} = $submission->{$userfield};
729 }
730 }
731 $activity->user->fullname = fullname($submission, $viewfullnames);
732
733 $activities[$index++] = $activity;
734 }
735
736 return;
737}
738
739/**
740 * Print recent activity from all assignments in a given course
741 *
742 * This is used by course/recent.php
743 * @param stdClass $activity
744 * @param int $courseid
745 * @param bool $detail
746 * @param array $modnames
747 */
e5403f8c 748function assign_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
bbd0e548
DW
749 global $CFG, $OUTPUT;
750
751 echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
752
e5403f8c 753 echo '<tr><td class="userpicture" valign="top">';
bbd0e548 754 echo $OUTPUT->user_picture($activity->user);
e5403f8c 755 echo '</td><td>';
bbd0e548
DW
756
757 if ($detail) {
758 $modname = $modnames[$activity->type];
759 echo '<div class="title">';
e5403f8c
DW
760 echo '<img src="' . $OUTPUT->pix_url('icon', 'assign') . '" '.
761 'class="icon" alt="' . $modname . '">';
762 echo '<a href="' . $CFG->wwwroot . '/mod/assign/view.php?id=' . $activity->cmid . '">';
763 echo $activity->name;
764 echo '</a>';
bbd0e548
DW
765 echo '</div>';
766 }
767
768 if (isset($activity->grade)) {
769 echo '<div class="grade">';
770 echo get_string('grade').': ';
771 echo $activity->grade;
772 echo '</div>';
773 }
774
775 echo '<div class="user">';
e5403f8c
DW
776 echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->id}&amp;course=$courseid\">";
777 echo "{$activity->user->fullname}</a> - " . userdate($activity->timestamp);
bbd0e548
DW
778 echo '</div>';
779
e5403f8c 780 echo '</td></tr></table>';
bbd0e548
DW
781}
782
783/**
e5403f8c 784 * Checks if a scale is being used by an assignment.
bbd0e548
DW
785 *
786 * This is used by the backup code to decide whether to back up a scale
9682626e 787 * @param int $assignmentid
bbd0e548
DW
788 * @param int $scaleid
789 * @return boolean True if the scale is used by the assignment
790 */
791function assign_scale_used($assignmentid, $scaleid) {
792 global $DB;
793
794 $return = false;
e5403f8c 795 $rec = $DB->get_record('assign', array('id'=>$assignmentid, 'grade'=>-$scaleid));
bbd0e548
DW
796
797 if (!empty($rec) && !empty($scaleid)) {
798 $return = true;
799 }
800
801 return $return;
802}
803
804/**
805 * Checks if scale is being used by any instance of assignment
806 *
807 * This is used to find out if scale used anywhere
9682626e 808 * @param int $scaleid
bbd0e548
DW
809 * @return boolean True if the scale is used by any assignment
810 */
811function assign_scale_used_anywhere($scaleid) {
812 global $DB;
813
814 if ($scaleid and $DB->record_exists('assign', array('grade'=>-$scaleid))) {
815 return true;
816 } else {
817 return false;
818 }
819}
820
821/**
e5403f8c
DW
822 * List the actions that correspond to a view of this module.
823 * This is used by the participation report.
bbd0e548
DW
824 * @return array
825 */
826function assign_get_view_actions() {
827 return array('view submission', 'view feedback');
828}
829
830/**
e5403f8c
DW
831 * List the actions that correspond to a post of this module.
832 * This is used by the participation report.
bbd0e548
DW
833 * @return array
834 */
835function assign_get_post_actions() {
836 return array('upload', 'submit', 'submit for grading');
837}
838
839/**
e5403f8c 840 * Call cron on the assign module.
bbd0e548
DW
841 */
842function assign_cron() {
843 global $CFG;
844
845 require_once($CFG->dirroot . '/mod/assign/locallib.php');
75f87a57
DW
846 assign::cron();
847
bbd0e548
DW
848 $plugins = get_plugin_list('assignsubmission');
849
850 foreach ($plugins as $name => $plugin) {
851 $disabled = get_config('assignsubmission_' . $name, 'disabled');
852 if (!$disabled) {
853 $class = 'assign_submission_' . $name;
854 require_once($CFG->dirroot . '/mod/assign/submission/' . $name . '/locallib.php');
855 $class::cron();
856 }
857 }
858 $plugins = get_plugin_list('assignfeedback');
859
860 foreach ($plugins as $name => $plugin) {
861 $disabled = get_config('assignfeedback_' . $name, 'disabled');
862 if (!$disabled) {
863 $class = 'assign_feedback_' . $name;
864 require_once($CFG->dirroot . '/mod/assign/feedback/' . $name . '/locallib.php');
865 $class::cron();
866 }
867 }
868}
869
870/**
871 * Returns all other capabilities used by this module.
872 * @return array Array of capability strings
873 */
874function assign_get_extra_capabilities() {
e5403f8c
DW
875 return array('gradereport/grader:view',
876 'moodle/grade:viewall',
877 'moodle/site:viewfullnames',
878 'moodle/site:config');
bbd0e548
DW
879}
880
881/**
e5403f8c 882 * Create grade item for given assignment.
bbd0e548
DW
883 *
884 * @param stdClass $assign record with extra cmidnumber
885 * @param array $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
886 * @return int 0 if ok, error code otherwise
887 */
e5403f8c 888function assign_grade_item_update($assign, $grades=null) {
bbd0e548
DW
889 global $CFG;
890 require_once($CFG->libdir.'/gradelib.php');
891
892 if (!isset($assign->courseid)) {
893 $assign->courseid = $assign->course;
894 }
895
896 $params = array('itemname'=>$assign->name, 'idnumber'=>$assign->cmidnumber);
897
898 if ($assign->grade > 0) {
899 $params['gradetype'] = GRADE_TYPE_VALUE;
900 $params['grademax'] = $assign->grade;
901 $params['grademin'] = 0;
902
903 } else if ($assign->grade < 0) {
904 $params['gradetype'] = GRADE_TYPE_SCALE;
905 $params['scaleid'] = -$assign->grade;
906
907 } else {
e5403f8c
DW
908 // Allow text comments only.
909 $params['gradetype'] = GRADE_TYPE_TEXT;
bbd0e548
DW
910 }
911
912 if ($grades === 'reset') {
913 $params['reset'] = true;
e5403f8c 914 $grades = null;
bbd0e548
DW
915 }
916
e5403f8c
DW
917 return grade_update('mod/assign',
918 $assign->courseid,
919 'mod',
920 'assign',
921 $assign->id,
922 0,
923 $grades,
924 $params);
bbd0e548
DW
925}
926
927/**
928 * Return grade for given user or all users.
929 *
930 * @param stdClass $assign record of assign with an additional cmidnumber
931 * @param int $userid optional user id, 0 means all users
932 * @return array array of grades, false if none
933 */
934function assign_get_user_grades($assign, $userid=0) {
935 global $CFG;
e5403f8c 936
bbd0e548
DW
937 require_once($CFG->dirroot . '/mod/assign/locallib.php');
938
79e7dfcc
RW
939 $cm = get_coursemodule_from_instance('assign', $assign->id, 0, false, MUST_EXIST);
940 $context = context_module::instance($cm->id);
941 $assignment = new assign($context, null, null);
b11808c7 942 $assignment->set_instance($assign);
bbd0e548
DW
943 return $assignment->get_user_grades_for_gradebook($userid);
944}
945
946/**
e5403f8c 947 * Update activity grades.
bbd0e548
DW
948 *
949 * @param stdClass $assign database record
950 * @param int $userid specific user only, 0 means all
951 * @param bool $nullifnone - not used
952 */
953function assign_update_grades($assign, $userid=0, $nullifnone=true) {
954 global $CFG;
955 require_once($CFG->libdir.'/gradelib.php');
956
957 if ($assign->grade == 0) {
958 assign_grade_item_update($assign);
959
960 } else if ($grades = assign_get_user_grades($assign, $userid)) {
e5403f8c 961 foreach ($grades as $k => $v) {
bbd0e548
DW
962 if ($v->rawgrade == -1) {
963 $grades[$k]->rawgrade = null;
964 }
965 }
966 assign_grade_item_update($assign, $grades);
967
968 } else {
969 assign_grade_item_update($assign);
970 }
971}
972
973/**
e5403f8c 974 * List the file areas that can be browsed.
bbd0e548
DW
975 *
976 * @param stdClass $course
977 * @param stdClass $cm
978 * @param stdClass $context
979 * @return array
980 */
6b8b0b2e 981function assign_get_file_areas($course, $cm, $context) {
bbd0e548
DW
982 global $CFG;
983 require_once($CFG->dirroot . '/mod/assign/locallib.php');
984 $areas = array();
985
986 $assignment = new assign($context, $cm, $course);
987 foreach ($assignment->get_submission_plugins() as $plugin) {
988 if ($plugin->is_visible()) {
989 $pluginareas = $plugin->get_file_areas();
990
991 if ($pluginareas) {
992 $areas = array_merge($areas, $pluginareas);
993 }
994 }
995 }
996 foreach ($assignment->get_feedback_plugins() as $plugin) {
997 if ($plugin->is_visible()) {
998 $pluginareas = $plugin->get_file_areas();
999
1000 if ($pluginareas) {
1001 $areas = array_merge($areas, $pluginareas);
1002 }
1003 }
1004 }
1005
1006 return $areas;
1007}
1008
1009/**
1010 * File browsing support for assign module.
1011 *
1012 * @param file_browser $browser
1013 * @param object $areas
1014 * @param object $course
1015 * @param object $cm
1016 * @param object $context
1017 * @param string $filearea
1018 * @param int $itemid
1019 * @param string $filepath
1020 * @param string $filename
1021 * @return object file_info instance or null if not found
1022 */
e5403f8c
DW
1023function assign_get_file_info($browser,
1024 $areas,
1025 $course,
1026 $cm,
1027 $context,
1028 $filearea,
1029 $itemid,
1030 $filepath,
1031 $filename) {
bbd0e548
DW
1032 global $CFG;
1033 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1034
1035 if ($context->contextlevel != CONTEXT_MODULE) {
1036 return null;
1037 }
1038
1039 $fs = get_file_storage();
1040 $filepath = is_null($filepath) ? '/' : $filepath;
1041 $filename = is_null($filename) ? '.' : $filename;
1042
e5403f8c 1043 // Need to find the plugin this belongs to.
bbd0e548
DW
1044 $assignment = new assign($context, $cm, $course);
1045 $pluginowner = null;
1046 foreach ($assignment->get_submission_plugins() as $plugin) {
1047 if ($plugin->is_visible()) {
1048 $pluginareas = $plugin->get_file_areas();
1049
1050 if (array_key_exists($filearea, $pluginareas)) {
1051 $pluginowner = $plugin;
1052 break;
1053 }
1054 }
1055 }
1056 if (!$pluginowner) {
1057 foreach ($assignment->get_feedback_plugins() as $plugin) {
1058 if ($plugin->is_visible()) {
1059 $pluginareas = $plugin->get_file_areas();
1060
1061 if (array_key_exists($filearea, $pluginareas)) {
1062 $pluginowner = $plugin;
1063 break;
1064 }
1065 }
1066 }
1067 }
1068
1069 if (!$pluginowner) {
1070 return null;
1071 }
1072
1073 $result = $pluginowner->get_file_info($browser, $filearea, $itemid, $filepath, $filename);
1074 return $result;
1075}
1076
1077/**
e5403f8c 1078 * Prints the complete info about a user's interaction with an assignment.
bbd0e548
DW
1079 *
1080 * @param stdClass $course
1081 * @param stdClass $user
1082 * @param stdClass $coursemodule
1083 * @param stdClass $assign the database assign record
1084 *
e5403f8c 1085 * This prints the submission summary and feedback summary for this student.
bbd0e548
DW
1086 */
1087function assign_user_complete($course, $user, $coursemodule, $assign) {
1088 global $CFG;
1089 require_once($CFG->dirroot . '/mod/assign/locallib.php');
e5403f8c 1090
bbd0e548
DW
1091 $context = context_module::instance($coursemodule->id);
1092
1093 $assignment = new assign($context, $coursemodule, $course);
1094
1095 echo $assignment->view_student_summary($user, false);
1096}
1097
1098/**
e5403f8c 1099 * Print the grade information for the assignment for this user.
9682626e 1100 *
bbd0e548
DW
1101 * @param stdClass $course
1102 * @param stdClass $user
1103 * @param stdClass $coursemodule
1104 * @param stdClass $assignment
1105 */
1106function assign_user_outline($course, $user, $coursemodule, $assignment) {
1107 global $CFG;
1108 require_once($CFG->libdir.'/gradelib.php');
1109 require_once($CFG->dirroot.'/grade/grading/lib.php');
1110
1111 $gradinginfo = grade_get_grades($course->id,
1112 'mod',
1113 'assign',
1114 $assignment->id,
1115 $user->id);
1116
1117 $gradingitem = $gradinginfo->items[0];
1118 $gradebookgrade = $gradingitem->grades[$user->id];
1119
1120 if (!$gradebookgrade) {
1121 return null;
1122 }
1123 $result = new stdClass();
1124 $result->info = get_string('outlinegrade', 'assign', $gradebookgrade->grade);
1125 $result->time = $gradebookgrade->dategraded;
1126
1127 return $result;
1128}
79ed4d84
DW
1129
1130/**
1131 * Obtains the automatic completion state for this module based on any conditions
1132 * in assign settings.
1133 *
1134 * @param object $course Course
1135 * @param object $cm Course-module
1136 * @param int $userid User ID
1137 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
1138 * @return bool True if completed, false if not, $type if conditions not set.
1139 */
3a66d425 1140function assign_get_completion_state($course, $cm, $userid, $type) {
e5403f8c 1141 global $CFG, $DB;
79ed4d84
DW
1142 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1143
1144 $assign = new assign(null, $cm, $course);
1145
3a66d425
DP
1146 // If completion option is enabled, evaluate it and return true/false.
1147 if ($assign->get_instance()->completionsubmit) {
e5403f8c
DW
1148 $dbparams = array('assignment'=>$assign->get_instance()->id, 'userid'=>$userid);
1149 $submission = $DB->get_record('assign_submission', $dbparams, '*', IGNORE_MISSING);
79ed4d84
DW
1150 return $submission && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1151 } else {
3a66d425 1152 // Completion option is not enabled so just return $type.
79ed4d84
DW
1153 return $type;
1154 }
1155}