MDL-35127 mod_assign More efficient use of expensive database queries
[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
bbd0e548 340 foreach ($assignments as $assignment) {
e5403f8c 341 // Do not show assignments that are not open.
da099b12
DW
342 if (!in_array($assignment->id, $assignmentids)) {
343 continue;
344 }
e5403f8c
DW
345 $dimmedclass = '';
346 if (!$assignment->visible) {
347 $dimmedclass = ' class="dimmed"';
348 }
349 $href = $CFG->wwwroot . '/mod/assign/view.php?id=' . $assignment->coursemodule;
350 $str = '<div class="assign overview">' .
351 '<div class="name">' .
352 $strassignment . ': '.
353 '<a ' . $dimmedclass .
354 'title="' . $strassignment . '" ' .
355 'href="' . $href . '">' .
356 format_string($assignment->name) .
357 '</a></div>';
bbd0e548 358 if ($assignment->duedate) {
e5403f8c
DW
359 $userdate = userdate($assignment->duedate);
360 $str .= '<div class="info">' . $strduedate . ': ' . $userdate . '</div>';
bbd0e548 361 } else {
e5403f8c 362 $str .= '<div class="info">' . $strduedateno . '</div>';
bbd0e548 363 }
9e795179
DW
364 if ($assignment->cutoffdate) {
365 if ($assignment->cutoffdate == $assignment->duedate) {
e5403f8c 366 $str .= '<div class="info">' . $strnolatesubmissions . '</div>';
9e795179 367 } else {
e5403f8c
DW
368 $userdate = userdate($assignment->cutoffdate);
369 $str .= '<div class="info">' . $strcutoffdate . ': ' . $userdate . '</div>';
9e795179
DW
370 }
371 }
bbd0e548
DW
372 $context = context_module::instance($assignment->coursemodule);
373 if (has_capability('mod/assign:grade', $context)) {
d77731d6
EM
374 if (!isset($unmarkedsubmissions)) {
375 // Build up and array of unmarked submissions indexed by assignment id/ userid
376 // for use where the user has grading rights on assignment.
377 $dbparams = array_merge(array(ASSIGN_SUBMISSION_STATUS_SUBMITTED), $assignmentidparams);
378 $rs = $DB->get_recordset_sql('SELECT
379 s.assignment as assignment,
380 s.userid as userid,
381 s.id as id,
382 s.status as status,
383 g.timemodified as timegraded
384 FROM {assign_submission} s
385 LEFT JOIN {assign_grades} g ON
386 s.userid = g.userid AND
387 s.assignment = g.assignment
388 WHERE
389 ( g.timemodified is NULL OR
390 s.timemodified > g.timemodified ) AND
391 s.timemodified IS NOT NULL AND
392 s.status = ? AND
393 s.assignment ' . $sqlassignmentids, $dbparams);
394
395 $unmarkedsubmissions = array();
396 foreach ($rs as $rd) {
397 $unmarkedsubmissions[$rd->assignment][$rd->userid] = $rd->id;
398 }
399 $rs->close();
400 }
401
e5403f8c
DW
402 // Count how many people can submit.
403 $submissions = 0;
bbd0e548
DW
404 if ($students = get_enrolled_users($context, 'mod/assign:view', 0, 'u.id')) {
405 foreach ($students as $student) {
406 if (isset($unmarkedsubmissions[$assignment->id][$student->id])) {
407 $submissions++;
408 }
409 }
410 }
411
412 if ($submissions) {
e5403f8c
DW
413 $urlparams = array('id'=>$assignment->coursemodule, 'action'=>'grading');
414 $url = new moodle_url('/mod/assign/view.php', $urlparams);
415 $str .= '<div class="details">' .
416 '<a href="' . $url . '">' .
417 get_string('submissionsnotgraded', 'assign', $submissions) .
418 '</a></div>';
bbd0e548 419 }
e5403f8c
DW
420 }
421 if (has_capability('mod/assign:submit', $context)) {
d77731d6
EM
422 if (!isset($mysubmissions)) {
423 // Get all user submissions, indexed by assignment id.
424 $dbparams = array_merge(array($USER->id, $USER->id), $assignmentidparams);
425 $mysubmissions = $DB->get_records_sql('SELECT
426 a.id AS assignment,
427 a.nosubmissions AS nosubmissions,
428 g.timemodified AS timemarked,
429 g.grader AS grader,
430 g.grade AS grade,
431 s.status AS status
432 FROM {assign} a
433 LEFT JOIN {assign_grades} g ON
434 g.assignment = a.id AND
435 g.userid = ?
436 LEFT JOIN {assign_submission} s ON
437 s.assignment = a.id AND
438 s.userid = ?
439 WHERE a.id ' . $sqlassignmentids, $dbparams);
440 }
441
bbd0e548
DW
442 $str .= '<div class="details">';
443 $str .= get_string('mysubmission', 'assign');
444 $submission = $mysubmissions[$assignment->id];
93c18e73 445 if ($submission->nosubmissions) {
e5403f8c
DW
446 $str .= get_string('offline', 'assign');
447 } else if (!$submission->status || $submission->status == 'draft') {
448 $str .= $strnotsubmittedyet;
449 } else {
bbd0e548
DW
450 $str .= get_string('submissionstatus_' . $submission->status, 'assign');
451 }
452 if (!$submission->grade || $submission->grade < 0) {
453 $str .= ', ' . get_string('notgraded', 'assign');
454 } else {
455 $str .= ', ' . get_string('graded', 'assign');
456 }
457 $str .= '</div>';
458 }
e5403f8c 459 $str .= '</div>';
bbd0e548
DW
460 if (empty($htmlarray[$assignment->course]['assign'])) {
461 $htmlarray[$assignment->course]['assign'] = $str;
462 } else {
463 $htmlarray[$assignment->course]['assign'] .= $str;
464 }
465 }
466}
467
468/**
469 * Print recent activity from all assignments in a given course
470 *
471 * This is used by the recent activity block
472 * @param mixed $course the course to print activity for
473 * @param bool $viewfullnames boolean to determine whether to show full names or not
9682626e 474 * @param int $timestart the time the rendering started
bbd0e548
DW
475 */
476function assign_print_recent_activity($course, $viewfullnames, $timestart) {
477 global $CFG, $USER, $DB, $OUTPUT;
478
e5403f8c 479 // Do not use log table if possible, it may be huge.
bbd0e548 480
e5403f8c
DW
481 $dbparams = array($timestart, $course->id, 'assign');
482 if (!$submissions = $DB->get_records_sql('SELECT asb.id, asb.timemodified, cm.id AS cmid, asb.userid,
bbd0e548
DW
483 u.firstname, u.lastname, u.email, u.picture
484 FROM {assign_submission} asb
485 JOIN {assign} a ON a.id = asb.assignment
486 JOIN {course_modules} cm ON cm.instance = a.id
487 JOIN {modules} md ON md.id = cm.module
488 JOIN {user} u ON u.id = asb.userid
489 WHERE asb.timemodified > ? AND
490 a.course = ? AND
e5403f8c
DW
491 md.name = ?
492 ORDER BY asb.timemodified ASC', $dbparams)) {
bbd0e548
DW
493 return false;
494 }
495
e5403f8c 496 $modinfo = get_fast_modinfo($course);
bbd0e548
DW
497 $show = array();
498 $grader = array();
499
cfc81f03
DW
500 $showrecentsubmissions = get_config('mod_assign', 'showrecentsubmissions');
501
e5403f8c 502 foreach ($submissions as $submission) {
bbd0e548
DW
503 if (!array_key_exists($submission->cmid, $modinfo->get_cms())) {
504 continue;
505 }
506 $cm = $modinfo->get_cm($submission->cmid);
507 if (!$cm->uservisible) {
508 continue;
509 }
510 if ($submission->userid == $USER->id) {
511 $show[] = $submission;
512 continue;
513 }
514
515 $context = context_module::instance($submission->cmid);
e5403f8c
DW
516 // The act of submitting of assignment may be considered private -
517 // only graders will see it if specified.
cfc81f03 518 if (empty($showrecentsubmissions)) {
bbd0e548 519 if (!array_key_exists($cm->id, $grader)) {
e5403f8c 520 $grader[$cm->id] = has_capability('moodle/grade:viewall', $context);
bbd0e548
DW
521 }
522 if (!$grader[$cm->id]) {
523 continue;
524 }
525 }
526
527 $groupmode = groups_get_activity_groupmode($cm, $course);
528
e5403f8c
DW
529 if ($groupmode == SEPARATEGROUPS &&
530 !has_capability('moodle/site:accessallgroups', $context)) {
bbd0e548 531 if (isguestuser()) {
e5403f8c 532 // Shortcut - guest user does not belong into any group.
bbd0e548
DW
533 continue;
534 }
535
536 if (is_null($modinfo->get_groups())) {
e5403f8c
DW
537 // Load all my groups and cache it in modinfo.
538 $modinfo->groups = groups_get_user_groups($course->id);
bbd0e548
DW
539 }
540
e5403f8c 541 // This will be slow - show only users that share group with me in this cm.
bbd0e548
DW
542 if (empty($modinfo->groups[$cm->id])) {
543 continue;
544 }
545 $usersgroups = groups_get_all_groups($course->id, $submission->userid, $cm->groupingid);
546 if (is_array($usersgroups)) {
547 $usersgroups = array_keys($usersgroups);
548 $intersect = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
549 if (empty($intersect)) {
550 continue;
551 }
552 }
553 }
554 $show[] = $submission;
555 }
556
557 if (empty($show)) {
558 return false;
559 }
560
561 echo $OUTPUT->heading(get_string('newsubmissions', 'assign').':', 3);
562
563 foreach ($show as $submission) {
564 $cm = $modinfo->get_cm($submission->cmid);
565 $link = $CFG->wwwroot.'/mod/assign/view.php?id='.$cm->id;
e5403f8c
DW
566 print_recent_activity_note($submission->timemodified,
567 $submission,
568 $cm->name,
569 $link,
570 false,
571 $viewfullnames);
bbd0e548
DW
572 }
573
574 return true;
575}
576
577/**
e5403f8c 578 * Returns all assignments since a given time.
c06b2127 579 *
bbd0e548
DW
580 * @param array $activities The activity information is returned in this array
581 * @param int $index The current index in the activities array
582 * @param int $timestart The earliest activity to show
583 * @param int $courseid Limit the search to this course
584 * @param int $cmid The course module id
585 * @param int $userid Optional user id
586 * @param int $groupid Optional group id
587 * @return void
588 */
e5403f8c
DW
589function assign_get_recent_mod_activity(&$activities,
590 &$index,
591 $timestart,
592 $courseid,
593 $cmid,
594 $userid=0,
595 $groupid=0) {
bbd0e548
DW
596 global $CFG, $COURSE, $USER, $DB;
597
598 if ($COURSE->id == $courseid) {
599 $course = $COURSE;
600 } else {
601 $course = $DB->get_record('course', array('id'=>$courseid));
602 }
603
e5403f8c 604 $modinfo = get_fast_modinfo($course);
bbd0e548
DW
605
606 $cm = $modinfo->get_cm($cmid);
607 $params = array();
608 if ($userid) {
e5403f8c 609 $userselect = 'AND u.id = :userid';
bbd0e548
DW
610 $params['userid'] = $userid;
611 } else {
e5403f8c 612 $userselect = '';
bbd0e548
DW
613 }
614
615 if ($groupid) {
e5403f8c
DW
616 $groupselect = 'AND gm.groupid = :groupid';
617 $groupjoin = 'JOIN {groups_members} gm ON gm.userid=u.id';
bbd0e548
DW
618 $params['groupid'] = $groupid;
619 } else {
e5403f8c
DW
620 $groupselect = '';
621 $groupjoin = '';
bbd0e548
DW
622 }
623
624 $params['cminstance'] = $cm->instance;
625 $params['timestart'] = $timestart;
626
627 $userfields = user_picture::fields('u', null, 'userid');
628
f93fdcef
DW
629 if (!$submissions = $DB->get_records_sql('SELECT asb.id, asb.timemodified, ' .
630 $userfields .
631 ' FROM {assign_submission} asb
632 JOIN {assign} a ON a.id = asb.assignment
633 JOIN {user} u ON u.id = asb.userid ' .
634 $groupjoin .
635 ' WHERE asb.timemodified > :timestart AND
e5403f8c
DW
636 a.id = :cminstance
637 ' . $userselect . ' ' . $groupselect .
638 ' ORDER BY asb.timemodified ASC', $params)) {
bbd0e548
DW
639 return;
640 }
641
642 $groupmode = groups_get_activity_groupmode($cm, $course);
643 $cm_context = context_module::instance($cm->id);
644 $grader = has_capability('moodle/grade:viewall', $cm_context);
645 $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
646 $viewfullnames = has_capability('moodle/site:viewfullnames', $cm_context);
647
648 if (is_null($modinfo->get_groups())) {
e5403f8c
DW
649 // Load all my groups and cache it in modinfo.
650 $modinfo->groups = groups_get_user_groups($course->id);
bbd0e548
DW
651 }
652
cfc81f03 653 $showrecentsubmissions = get_config('mod_assign', 'showrecentsubmissions');
bbd0e548
DW
654 $show = array();
655 $usersgroups = groups_get_all_groups($course->id, $USER->id, $cm->groupingid);
656 if (is_array($usersgroups)) {
657 $usersgroups = array_keys($usersgroups);
658 }
e5403f8c 659 foreach ($submissions as $submission) {
bbd0e548
DW
660 if ($submission->userid == $USER->id) {
661 $show[] = $submission;
662 continue;
663 }
e5403f8c
DW
664 // The act of submitting of assignment may be considered private -
665 // only graders will see it if specified.
cfc81f03 666 if (empty($showrecentsubmissions)) {
bbd0e548
DW
667 if (!$grader) {
668 continue;
669 }
670 }
671
672 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
673 if (isguestuser()) {
e5403f8c 674 // Shortcut - guest user does not belong into any group.
bbd0e548
DW
675 continue;
676 }
677
e5403f8c 678 // This will be slow - show only users that share group with me in this cm.
bbd0e548
DW
679 if (empty($modinfo->groups[$cm->id])) {
680 continue;
681 }
682 if (is_array($usersgroups)) {
683 $intersect = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
684 if (empty($intersect)) {
685 continue;
686 }
687 }
688 }
689 $show[] = $submission;
690 }
691
692 if (empty($show)) {
693 return;
694 }
695
696 if ($grader) {
697 require_once($CFG->libdir.'/gradelib.php');
698 $userids = array();
e5403f8c 699 foreach ($show as $id => $submission) {
bbd0e548 700 $userids[] = $submission->userid;
bbd0e548
DW
701 }
702 $grades = grade_get_grades($courseid, 'mod', 'assign', $cm->instance, $userids);
703 }
704
e5403f8c 705 $aname = format_string($cm->name, true);
bbd0e548
DW
706 foreach ($show as $submission) {
707 $activity = new stdClass();
708
709 $activity->type = 'assign';
710 $activity->cmid = $cm->id;
711 $activity->name = $aname;
712 $activity->sectionnum = $cm->sectionnum;
713 $activity->timestamp = $submission->timemodified;
714 $activity->user = new stdClass();
715 if ($grader) {
716 $activity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
717 }
718
719 $userfields = explode(',', user_picture::fields());
720 foreach ($userfields as $userfield) {
721 if ($userfield == 'id') {
e5403f8c
DW
722 // Aliased in SQL above.
723 $activity->user->{$userfield} = $submission->userid;
bbd0e548
DW
724 } else {
725 $activity->user->{$userfield} = $submission->{$userfield};
726 }
727 }
728 $activity->user->fullname = fullname($submission, $viewfullnames);
729
730 $activities[$index++] = $activity;
731 }
732
733 return;
734}
735
736/**
737 * Print recent activity from all assignments in a given course
738 *
739 * This is used by course/recent.php
740 * @param stdClass $activity
741 * @param int $courseid
742 * @param bool $detail
743 * @param array $modnames
744 */
e5403f8c 745function assign_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
bbd0e548
DW
746 global $CFG, $OUTPUT;
747
748 echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
749
e5403f8c 750 echo '<tr><td class="userpicture" valign="top">';
bbd0e548 751 echo $OUTPUT->user_picture($activity->user);
e5403f8c 752 echo '</td><td>';
bbd0e548
DW
753
754 if ($detail) {
755 $modname = $modnames[$activity->type];
756 echo '<div class="title">';
e5403f8c
DW
757 echo '<img src="' . $OUTPUT->pix_url('icon', 'assign') . '" '.
758 'class="icon" alt="' . $modname . '">';
759 echo '<a href="' . $CFG->wwwroot . '/mod/assign/view.php?id=' . $activity->cmid . '">';
760 echo $activity->name;
761 echo '</a>';
bbd0e548
DW
762 echo '</div>';
763 }
764
765 if (isset($activity->grade)) {
766 echo '<div class="grade">';
767 echo get_string('grade').': ';
768 echo $activity->grade;
769 echo '</div>';
770 }
771
772 echo '<div class="user">';
e5403f8c
DW
773 echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->id}&amp;course=$courseid\">";
774 echo "{$activity->user->fullname}</a> - " . userdate($activity->timestamp);
bbd0e548
DW
775 echo '</div>';
776
e5403f8c 777 echo '</td></tr></table>';
bbd0e548
DW
778}
779
780/**
e5403f8c 781 * Checks if a scale is being used by an assignment.
bbd0e548
DW
782 *
783 * This is used by the backup code to decide whether to back up a scale
9682626e 784 * @param int $assignmentid
bbd0e548
DW
785 * @param int $scaleid
786 * @return boolean True if the scale is used by the assignment
787 */
788function assign_scale_used($assignmentid, $scaleid) {
789 global $DB;
790
791 $return = false;
e5403f8c 792 $rec = $DB->get_record('assign', array('id'=>$assignmentid, 'grade'=>-$scaleid));
bbd0e548
DW
793
794 if (!empty($rec) && !empty($scaleid)) {
795 $return = true;
796 }
797
798 return $return;
799}
800
801/**
802 * Checks if scale is being used by any instance of assignment
803 *
804 * This is used to find out if scale used anywhere
9682626e 805 * @param int $scaleid
bbd0e548
DW
806 * @return boolean True if the scale is used by any assignment
807 */
808function assign_scale_used_anywhere($scaleid) {
809 global $DB;
810
811 if ($scaleid and $DB->record_exists('assign', array('grade'=>-$scaleid))) {
812 return true;
813 } else {
814 return false;
815 }
816}
817
818/**
e5403f8c
DW
819 * List the actions that correspond to a view of this module.
820 * This is used by the participation report.
bbd0e548
DW
821 * @return array
822 */
823function assign_get_view_actions() {
824 return array('view submission', 'view feedback');
825}
826
827/**
e5403f8c
DW
828 * List the actions that correspond to a post of this module.
829 * This is used by the participation report.
bbd0e548
DW
830 * @return array
831 */
832function assign_get_post_actions() {
833 return array('upload', 'submit', 'submit for grading');
834}
835
836/**
e5403f8c 837 * Call cron on the assign module.
bbd0e548
DW
838 */
839function assign_cron() {
840 global $CFG;
841
842 require_once($CFG->dirroot . '/mod/assign/locallib.php');
75f87a57
DW
843 assign::cron();
844
bbd0e548
DW
845 $plugins = get_plugin_list('assignsubmission');
846
847 foreach ($plugins as $name => $plugin) {
848 $disabled = get_config('assignsubmission_' . $name, 'disabled');
849 if (!$disabled) {
850 $class = 'assign_submission_' . $name;
851 require_once($CFG->dirroot . '/mod/assign/submission/' . $name . '/locallib.php');
852 $class::cron();
853 }
854 }
855 $plugins = get_plugin_list('assignfeedback');
856
857 foreach ($plugins as $name => $plugin) {
858 $disabled = get_config('assignfeedback_' . $name, 'disabled');
859 if (!$disabled) {
860 $class = 'assign_feedback_' . $name;
861 require_once($CFG->dirroot . '/mod/assign/feedback/' . $name . '/locallib.php');
862 $class::cron();
863 }
864 }
865}
866
867/**
868 * Returns all other capabilities used by this module.
869 * @return array Array of capability strings
870 */
871function assign_get_extra_capabilities() {
e5403f8c
DW
872 return array('gradereport/grader:view',
873 'moodle/grade:viewall',
874 'moodle/site:viewfullnames',
875 'moodle/site:config');
bbd0e548
DW
876}
877
878/**
e5403f8c 879 * Create grade item for given assignment.
bbd0e548
DW
880 *
881 * @param stdClass $assign record with extra cmidnumber
882 * @param array $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
883 * @return int 0 if ok, error code otherwise
884 */
e5403f8c 885function assign_grade_item_update($assign, $grades=null) {
bbd0e548
DW
886 global $CFG;
887 require_once($CFG->libdir.'/gradelib.php');
888
889 if (!isset($assign->courseid)) {
890 $assign->courseid = $assign->course;
891 }
892
893 $params = array('itemname'=>$assign->name, 'idnumber'=>$assign->cmidnumber);
894
895 if ($assign->grade > 0) {
896 $params['gradetype'] = GRADE_TYPE_VALUE;
897 $params['grademax'] = $assign->grade;
898 $params['grademin'] = 0;
899
900 } else if ($assign->grade < 0) {
901 $params['gradetype'] = GRADE_TYPE_SCALE;
902 $params['scaleid'] = -$assign->grade;
903
904 } else {
e5403f8c
DW
905 // Allow text comments only.
906 $params['gradetype'] = GRADE_TYPE_TEXT;
bbd0e548
DW
907 }
908
909 if ($grades === 'reset') {
910 $params['reset'] = true;
e5403f8c 911 $grades = null;
bbd0e548
DW
912 }
913
e5403f8c
DW
914 return grade_update('mod/assign',
915 $assign->courseid,
916 'mod',
917 'assign',
918 $assign->id,
919 0,
920 $grades,
921 $params);
bbd0e548
DW
922}
923
924/**
925 * Return grade for given user or all users.
926 *
927 * @param stdClass $assign record of assign with an additional cmidnumber
928 * @param int $userid optional user id, 0 means all users
929 * @return array array of grades, false if none
930 */
931function assign_get_user_grades($assign, $userid=0) {
932 global $CFG;
e5403f8c 933
bbd0e548
DW
934 require_once($CFG->dirroot . '/mod/assign/locallib.php');
935
79e7dfcc
RW
936 $cm = get_coursemodule_from_instance('assign', $assign->id, 0, false, MUST_EXIST);
937 $context = context_module::instance($cm->id);
938 $assignment = new assign($context, null, null);
b11808c7 939 $assignment->set_instance($assign);
bbd0e548
DW
940 return $assignment->get_user_grades_for_gradebook($userid);
941}
942
943/**
e5403f8c 944 * Update activity grades.
bbd0e548
DW
945 *
946 * @param stdClass $assign database record
947 * @param int $userid specific user only, 0 means all
948 * @param bool $nullifnone - not used
949 */
950function assign_update_grades($assign, $userid=0, $nullifnone=true) {
951 global $CFG;
952 require_once($CFG->libdir.'/gradelib.php');
953
954 if ($assign->grade == 0) {
955 assign_grade_item_update($assign);
956
957 } else if ($grades = assign_get_user_grades($assign, $userid)) {
e5403f8c 958 foreach ($grades as $k => $v) {
bbd0e548
DW
959 if ($v->rawgrade == -1) {
960 $grades[$k]->rawgrade = null;
961 }
962 }
963 assign_grade_item_update($assign, $grades);
964
965 } else {
966 assign_grade_item_update($assign);
967 }
968}
969
970/**
e5403f8c 971 * List the file areas that can be browsed.
bbd0e548
DW
972 *
973 * @param stdClass $course
974 * @param stdClass $cm
975 * @param stdClass $context
976 * @return array
977 */
6b8b0b2e 978function assign_get_file_areas($course, $cm, $context) {
bbd0e548
DW
979 global $CFG;
980 require_once($CFG->dirroot . '/mod/assign/locallib.php');
981 $areas = array();
982
983 $assignment = new assign($context, $cm, $course);
984 foreach ($assignment->get_submission_plugins() as $plugin) {
985 if ($plugin->is_visible()) {
986 $pluginareas = $plugin->get_file_areas();
987
988 if ($pluginareas) {
989 $areas = array_merge($areas, $pluginareas);
990 }
991 }
992 }
993 foreach ($assignment->get_feedback_plugins() as $plugin) {
994 if ($plugin->is_visible()) {
995 $pluginareas = $plugin->get_file_areas();
996
997 if ($pluginareas) {
998 $areas = array_merge($areas, $pluginareas);
999 }
1000 }
1001 }
1002
1003 return $areas;
1004}
1005
1006/**
1007 * File browsing support for assign module.
1008 *
1009 * @param file_browser $browser
1010 * @param object $areas
1011 * @param object $course
1012 * @param object $cm
1013 * @param object $context
1014 * @param string $filearea
1015 * @param int $itemid
1016 * @param string $filepath
1017 * @param string $filename
1018 * @return object file_info instance or null if not found
1019 */
e5403f8c
DW
1020function assign_get_file_info($browser,
1021 $areas,
1022 $course,
1023 $cm,
1024 $context,
1025 $filearea,
1026 $itemid,
1027 $filepath,
1028 $filename) {
bbd0e548
DW
1029 global $CFG;
1030 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1031
1032 if ($context->contextlevel != CONTEXT_MODULE) {
1033 return null;
1034 }
1035
1036 $fs = get_file_storage();
1037 $filepath = is_null($filepath) ? '/' : $filepath;
1038 $filename = is_null($filename) ? '.' : $filename;
1039
e5403f8c 1040 // Need to find the plugin this belongs to.
bbd0e548
DW
1041 $assignment = new assign($context, $cm, $course);
1042 $pluginowner = null;
1043 foreach ($assignment->get_submission_plugins() as $plugin) {
1044 if ($plugin->is_visible()) {
1045 $pluginareas = $plugin->get_file_areas();
1046
1047 if (array_key_exists($filearea, $pluginareas)) {
1048 $pluginowner = $plugin;
1049 break;
1050 }
1051 }
1052 }
1053 if (!$pluginowner) {
1054 foreach ($assignment->get_feedback_plugins() as $plugin) {
1055 if ($plugin->is_visible()) {
1056 $pluginareas = $plugin->get_file_areas();
1057
1058 if (array_key_exists($filearea, $pluginareas)) {
1059 $pluginowner = $plugin;
1060 break;
1061 }
1062 }
1063 }
1064 }
1065
1066 if (!$pluginowner) {
1067 return null;
1068 }
1069
1070 $result = $pluginowner->get_file_info($browser, $filearea, $itemid, $filepath, $filename);
1071 return $result;
1072}
1073
1074/**
e5403f8c 1075 * Prints the complete info about a user's interaction with an assignment.
bbd0e548
DW
1076 *
1077 * @param stdClass $course
1078 * @param stdClass $user
1079 * @param stdClass $coursemodule
1080 * @param stdClass $assign the database assign record
1081 *
e5403f8c 1082 * This prints the submission summary and feedback summary for this student.
bbd0e548
DW
1083 */
1084function assign_user_complete($course, $user, $coursemodule, $assign) {
1085 global $CFG;
1086 require_once($CFG->dirroot . '/mod/assign/locallib.php');
e5403f8c 1087
bbd0e548
DW
1088 $context = context_module::instance($coursemodule->id);
1089
1090 $assignment = new assign($context, $coursemodule, $course);
1091
1092 echo $assignment->view_student_summary($user, false);
1093}
1094
1095/**
e5403f8c 1096 * Print the grade information for the assignment for this user.
9682626e 1097 *
bbd0e548
DW
1098 * @param stdClass $course
1099 * @param stdClass $user
1100 * @param stdClass $coursemodule
1101 * @param stdClass $assignment
1102 */
1103function assign_user_outline($course, $user, $coursemodule, $assignment) {
1104 global $CFG;
1105 require_once($CFG->libdir.'/gradelib.php');
1106 require_once($CFG->dirroot.'/grade/grading/lib.php');
1107
1108 $gradinginfo = grade_get_grades($course->id,
1109 'mod',
1110 'assign',
1111 $assignment->id,
1112 $user->id);
1113
1114 $gradingitem = $gradinginfo->items[0];
1115 $gradebookgrade = $gradingitem->grades[$user->id];
1116
1117 if (!$gradebookgrade) {
1118 return null;
1119 }
1120 $result = new stdClass();
1121 $result->info = get_string('outlinegrade', 'assign', $gradebookgrade->grade);
1122 $result->time = $gradebookgrade->dategraded;
1123
1124 return $result;
1125}
79ed4d84
DW
1126
1127/**
1128 * Obtains the automatic completion state for this module based on any conditions
1129 * in assign settings.
1130 *
1131 * @param object $course Course
1132 * @param object $cm Course-module
1133 * @param int $userid User ID
1134 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
1135 * @return bool True if completed, false if not, $type if conditions not set.
1136 */
3a66d425 1137function assign_get_completion_state($course, $cm, $userid, $type) {
e5403f8c 1138 global $CFG, $DB;
79ed4d84
DW
1139 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1140
1141 $assign = new assign(null, $cm, $course);
1142
3a66d425
DP
1143 // If completion option is enabled, evaluate it and return true/false.
1144 if ($assign->get_instance()->completionsubmit) {
e5403f8c
DW
1145 $dbparams = array('assignment'=>$assign->get_instance()->id, 'userid'=>$userid);
1146 $submission = $DB->get_record('assign_submission', $dbparams, '*', IGNORE_MISSING);
79ed4d84
DW
1147 return $submission && $submission->status == ASSIGN_SUBMISSION_STATUS_SUBMITTED;
1148 } else {
3a66d425 1149 // Completion option is not enabled so just return $type.
79ed4d84
DW
1150 return $type;
1151 }
1152}