Merge branch 'install_master' of git://github.com/amosbot/moodle
[moodle.git] / lib / completionlib.php
CommitLineData
4e781c7b 1<?php
4e781c7b 2
117bd748
PS
3// This file is part of Moodle - http://moodle.org/
4//
09639ded 5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
117bd748 14//
09639ded 15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
18/**
19 * Contains a class used for tracking whether activities have been completed
20 * by students ('completion')
21 *
22 * Completion top-level options (admin setting enablecompletion)
117bd748 23 *
78bfb562
PS
24 * @package core
25 * @subpackage completion
26 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
27 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
09639ded 28 */
4e781c7b 29
78bfb562
PS
30defined('MOODLE_INTERNAL') || die();
31
32require_once $CFG->libdir.'/completion/completion_aggregation.php';
33require_once $CFG->libdir.'/completion/completion_criteria.php';
34require_once $CFG->libdir.'/completion/completion_completion.php';
35require_once $CFG->libdir.'/completion/completion_criteria_completion.php';
36
37
4e781c7b 38/** The completion system is enabled in this site/course */
0d5d12bd 39define('COMPLETION_ENABLED', 1);
4e781c7b 40/** The completion system is not enabled in this site/course */
0d5d12bd 41define('COMPLETION_DISABLED', 0);
4e781c7b 42
43// Completion tracking options per-activity (course_modules/completion)
44
45/** Completion tracking is disabled for this activity */
0d5d12bd 46define('COMPLETION_TRACKING_NONE', 0);
4e781c7b 47/** Manual completion tracking (user ticks box) is enabled for this activity */
0d5d12bd 48define('COMPLETION_TRACKING_MANUAL', 1);
4e781c7b 49/** Automatic completion tracking (system ticks box) is enabled for this activity */
0d5d12bd 50define('COMPLETION_TRACKING_AUTOMATIC', 2);
4e781c7b 51
52// Completion state values (course_modules_completion/completionstate)
53
54/** The user has not completed this activity. */
0d5d12bd 55define('COMPLETION_INCOMPLETE', 0);
4e781c7b 56/** The user has completed this activity. It is not specified whether they have
57 * passed or failed it. */
0d5d12bd 58define('COMPLETION_COMPLETE', 1);
4e781c7b 59/** The user has completed this activity with a grade above the pass mark. */
0d5d12bd 60define('COMPLETION_COMPLETE_PASS', 2);
4e781c7b 61/** The user has completed this activity but their grade is less than the pass mark */
0d5d12bd 62define('COMPLETION_COMPLETE_FAIL', 3);
4e781c7b 63
0d5d12bd 64// Completion effect changes (used only in update_state)
4e781c7b 65
66/** The effect of this change to completion status is unknown. */
0d5d12bd 67define('COMPLETION_UNKNOWN', -1);
68/** The user's grade has changed, so their new state might be
4e781c7b 69 * COMPLETION_COMPLETE_PASS or COMPLETION_COMPLETE_FAIL. */
70// TODO Is this useful?
0d5d12bd 71define('COMPLETION_GRADECHANGE', -2);
4e781c7b 72
73// Whether view is required to create an activity (course_modules/completionview)
74
75/** User must view this activity */
0d5d12bd 76define('COMPLETION_VIEW_REQUIRED', 1);
4e781c7b 77/** User does not need to view this activity */
0d5d12bd 78define('COMPLETION_VIEW_NOT_REQUIRED', 0);
4e781c7b 79
80// Completion viewed state (course_modules_completion/viewed)
81
82/** User has viewed this activity */
0d5d12bd 83define('COMPLETION_VIEWED', 1);
4e781c7b 84/** User has not viewed this activity */
0d5d12bd 85define('COMPLETION_NOT_VIEWED', 0);
4e781c7b 86
87// Completion cacheing
88
89/** Cache expiry time in seconds (10 minutes) */
0d5d12bd 90define('COMPLETION_CACHE_EXPIRY', 10*60);
4e781c7b 91
92// Combining completion condition. This is also the value you should return
2be4d090 93// if you don't have any applicable conditions. Used for activity completion.
0d5d12bd 94/** Completion details should be ORed together and you should return false if
4e781c7b 95 none apply */
0d5d12bd 96define('COMPLETION_OR', false);
97/** Completion details should be ANDed together and you should return true if
4e781c7b 98 none apply */
0d5d12bd 99define('COMPLETION_AND', true);
4e781c7b 100
2be4d090
MD
101// Course completion criteria aggregation methods
102define('COMPLETION_AGGREGATION_ALL', 1);
103define('COMPLETION_AGGREGATION_ANY', 2);
104
105
4e781c7b 106/**
107 * Class represents completion information for a course.
09639ded 108 *
109 * Does not contain any data, so you can safely construct it multiple times
110 * without causing any problems.
111 *
112 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
113 * @package moodlecore
4e781c7b 114 */
115class completion_info {
78bfb562 116 /**
2be4d090
MD
117 * Course object passed during construction
118 * @access private
119 * @var object
120 */
4e781c7b 121 private $course;
0d5d12bd 122
2be4d090
MD
123 /**
124 * Course id
125 * @access public
126 * @var int
127 */
128 public $course_id;
129
130 /**
131 * Completion criteria
132 * @access private
133 * @var array
134 * @see completion_info->get_criteria()
135 */
136 private $criteria;
137
138 /**
139 * Return array of aggregation methods
140 * @access public
141 * @return array
142 */
143 public static function get_aggregation_methods() {
144 return array(
145 COMPLETION_AGGREGATION_ALL => get_string('all'),
146 COMPLETION_AGGREGATION_ANY => get_string('any', 'completion'),
147 );
148 }
149
4e781c7b 150 /**
151 * Constructs with course details.
152 *
153 * @param object $course Moodle course object. Must have at least ->id, ->enablecompletion
4e781c7b 154 */
49f6e5f4 155 public function __construct($course) {
0d5d12bd 156 $this->course = $course;
2be4d090 157 $this->course_id = $course->id;
4e781c7b 158 }
159
160 /**
09639ded 161 * Determines whether completion is enabled across entire site.
117bd748
PS
162 *
163 * Static function.
4e781c7b 164 *
09639ded 165 * @global object
0d5d12bd 166 * @return int COMPLETION_ENABLED (true) if completion is enabled for the site,
4e781c7b 167 * COMPLETION_DISABLED (false) if it's complete
168 */
169 public static function is_enabled_for_site() {
170 global $CFG;
1caea91e 171 return !empty($CFG->enablecompletion);
4e781c7b 172 }
0d5d12bd 173
4e781c7b 174 /**
175 * Checks whether completion is enabled in a particular course and possibly
176 * activity.
177 *
09639ded 178 * @global object
179 * @uses COMPLETION_DISABLED
180 * @uses COMPLETION_ENABLED
4e781c7b 181 * @param object $cm Course-module object. If not specified, returns the course
182 * completion enable state.
09639ded 183 * @return mixed COMPLETION_ENABLED or COMPLETION_DISABLED (==0) in the case of
4e781c7b 184 * site and course; COMPLETION_TRACKING_MANUAL, _AUTOMATIC or _NONE (==0)
185 * for a course-module.
186 */
187 public function is_enabled($cm=null) {
7075e37e 188 global $CFG, $DB;
d7d87535 189
190 // First check global completion
250c0533 191 if (!isset($CFG->enablecompletion) || $CFG->enablecompletion == COMPLETION_DISABLED) {
4e781c7b 192 return COMPLETION_DISABLED;
193 }
0d5d12bd 194
7075e37e
AB
195 // Load data if we do not have enough
196 if (!isset($this->course->enablecompletion)) {
197 $this->course->enablecompletion = $DB->get_field('course', 'enablecompletion', array('id' => $this->course->id));
198 }
199
4e781c7b 200 // Check course completion
0d5d12bd 201 if ($this->course->enablecompletion == COMPLETION_DISABLED) {
4e781c7b 202 return COMPLETION_DISABLED;
203 }
0d5d12bd 204
4e781c7b 205 // If there was no $cm and we got this far, then it's enabled
0d5d12bd 206 if (!$cm) {
4e781c7b 207 return COMPLETION_ENABLED;
208 }
0d5d12bd 209
4e781c7b 210 // Return course-module completion value
211 return $cm->completion;
212 }
0d5d12bd 213
2af26b12 214 /**
215 * Displays the 'Your progress' help icon, if completion tracking is enabled.
216 * Just prints the result of display_help_icon().
217 * @deprecated Use display_help_icon instead.
218 * @return void
219 */
220 public function print_help_icon() {
221 print $this->display_help_icon();
222 }
223
e3568fde 224 /**
563e97b8 225 * Returns the 'Your progress' help icon, if completion tracking is enabled.
e3568fde 226 * @global object
563e97b8 227 * @return string HTML code for help icon, or blank if not needed
e3568fde 228 */
563e97b8 229 public function display_help_icon() {
aa9a6867 230 global $PAGE, $OUTPUT;
563e97b8 231 $result = '';
e3568fde 232 if ($this->is_enabled() && !$PAGE->user_is_editing() && isloggedin() && !isguestuser()) {
563e97b8 233 $result .= '<span id = "completionprogressid" class="completionprogress">'.get_string('yourprogress','completion').' ';
234 $result .= $OUTPUT->help_icon('completionicons', 'completion');
235 $result .= '</span>';
e3568fde 236 }
563e97b8 237 return $result;
e3568fde 238 }
2be4d090
MD
239
240 /**
241 * Get a course completion for a user
242 * @access public
243 * @param $user_id int User id
244 * @param $criteriatype int Specific criteria type to return
245 * @return false|completion_criteria_completion
246 */
247 public function get_completion($user_id, $criteriatype) {
248 $completions = $this->get_completions($user_id, $criteriatype);
249
250 if (empty($completions)) {
251 return false;
252 } elseif (count($completions) > 1) {
253 print_error('multipleselfcompletioncriteria', 'completion');
254 }
255
256 return $completions[0];
257 }
258
259 /**
260 * Get all course criteria's completion objects for a user
261 * @access public
262 * @param $user_id int User id
263 * @param $criteriatype int optional Specific criteria type to return
264 * @return array
265 */
266 public function get_completions($user_id, $criteriatype = null) {
267 $criterion = $this->get_criteria($criteriatype);
268
269 $completions = array();
270
271 foreach ($criterion as $criteria) {
272 $params = array(
273 'course' => $this->course_id,
274 'userid' => $user_id,
275 'criteriaid' => $criteria->id
276 );
277
278 $completion = new completion_criteria_completion($params);
279 $completion->attach_criteria($criteria);
280
281 $completions[] = $completion;
282 }
283
284 return $completions;
285 }
286
287 /**
288 * Get completion object for a user and a criteria
289 * @access public
290 * @param $user_id int User id
291 * @param $criteria completion_criteria Criteria object
292 * @return completion_criteria_completion
293 */
294 public function get_user_completion($user_id, $criteria) {
295 $params = array(
296 'criteriaid' => $criteria->id,
297 'userid' => $user_id
298 );
299
300 $completion = new completion_criteria_completion($params);
301 return $completion;
302 }
303
304 /**
305 * Check if course has completion criteria set
306 *
307 * @access public
308 * @return bool
309 */
310 public function has_criteria() {
311 $criteria = $this->get_criteria();
312
313 return (bool) count($criteria);
314 }
315
316
317 /**
318 * Get course completion criteria
319 * @access public
320 * @param $criteriatype int optional Specific criteria type to return
321 * @return void
322 */
323 public function get_criteria($criteriatype = null) {
324
325 // Fill cache if empty
326 if (!is_array($this->criteria)) {
327 global $DB;
328
329 $params = array(
330 'course' => $this->course->id
331 );
332
333 // Load criteria from database
334 $records = (array)$DB->get_records('course_completion_criteria', $params);
335
336 // Build array of criteria objects
337 $this->criteria = array();
338 foreach ($records as $record) {
339 $this->criteria[$record->id] = completion_criteria::factory($record);
340 }
341 }
342
343 // If after all criteria
344 if ($criteriatype === null) {
345 return $this->criteria;
346 }
347
348 // If we are only after a specific criteria type
349 $criteria = array();
350 foreach ($this->criteria as $criterion) {
351
352 if ($criterion->criteriatype != $criteriatype) {
353 continue;
354 }
355
356 $criteria[$criterion->id] = $criterion;
357 }
358
359 return $criteria;
360 }
361
362 /**
363 * Get aggregation method
364 * @access public
365 * @param $criteriatype int optional If none supplied, get overall aggregation method
366 * @return int
367 */
368 public function get_aggregation_method($criteriatype = null) {
369 $params = array(
370 'course' => $this->course_id,
371 'criteriatype' => $criteriatype
372 );
373
374 $aggregation = new completion_aggregation($params);
375
376 if (!$aggregation->id) {
377 $aggregation->method = COMPLETION_AGGREGATION_ALL;
378 }
379
380 return $aggregation->method;
381 }
382
383 /**
384 * Get incomplete course completion criteria
385 * @access public
386 * @return void
387 */
388 public function get_incomplete_criteria() {
389 $incomplete = array();
390
391 foreach ($this->get_criteria() as $criteria) {
392 if (!$criteria->is_complete()) {
393 $incomplete[] = $criteria;
394 }
395 }
396
397 return $incomplete;
398 }
399
400 /**
401 * Clear old course completion criteria
402 */
403 public function clear_criteria() {
404 global $DB;
405 $DB->delete_records('course_completion_criteria', array('course' => $this->course_id));
406 $DB->delete_records('course_completion_aggr_methd', array('course' => $this->course_id));
407
408 $this->delete_course_completion_data();
409 }
410
411 /**
412 * Has the supplied user completed this course
413 * @access public
414 * @param $user_id int User's id
415 * @return boolean
416 */
417 public function is_course_complete($user_id) {
418 $params = array(
419 'userid' => $user_id,
420 'course' => $this->course_id
421 );
422
423 $ccompletion = new completion_completion($params);
424 return $ccompletion->is_complete();
425 }
426
4e781c7b 427 /**
428 * Updates (if necessary) the completion state of activity $cm for the given
429 * user.
09639ded 430 *
4e781c7b 431 * For manual completion, this function is called when completion is toggled
432 * with $possibleresult set to the target state.
09639ded 433 *
4e781c7b 434 * For automatic completion, this function should be called every time a module
435 * does something which might influence a user's completion state. For example,
436 * if a forum provides options for marking itself 'completed' once a user makes
437 * N posts, this function should be called every time a user makes a new post.
438 * [After the post has been saved to the database]. When calling, you do not
439 * need to pass in the new completion state. Instead this function carries out
440 * completion calculation by checking grades and viewed state itself, and
441 * calling the involved module via modulename_get_completion_state() to check
442 * module-specific conditions.
443 *
09639ded 444 * @global object
445 * @global object
446 * @uses COMPLETION_COMPLETE
447 * @uses COMPLETION_INCOMPLETE
448 * @uses COMPLETION_COMPLETE_PASS
449 * @uses COMPLETION_COMPLETE_FAIL
450 * @uses COMPLETION_TRACKING_MANUAL
4e781c7b 451 * @param object $cm Course-module
452 * @param int $possibleresult Expected completion result. If the event that
453 * has just occurred (e.g. add post) can only result in making the activity
454 * complete when it wasn't before, use COMPLETION_COMPLETE. If the event that
455 * has just occurred (e.g. delete post) can only result in making the activity
456 * not complete when it was previously complete, use COMPLETION_INCOMPLETE.
457 * Otherwise use COMPLETION_UNKNOWN. Setting this value to something other than
458 * COMPLETION_UNKNOWN significantly improves performance because it will abandon
459 * processing early if the user's completion state already matches the expected
460 * result. For manual events, COMPLETION_COMPLETE or COMPLETION_INCOMPLETE
461 * must be used; these directly set the specified state.
462 * @param int $userid User ID to be updated. Default 0 = current user
09639ded 463 * @return void
4e781c7b 464 */
0d5d12bd 465 public function update_state($cm, $possibleresult=COMPLETION_UNKNOWN, $userid=0) {
466 global $USER, $SESSION;
d7d87535 467
0d5d12bd 468 // Do nothing if completion is not enabled for that activity
469 if (!$this->is_enabled($cm)) {
4e781c7b 470 return;
471 }
0d5d12bd 472
4e781c7b 473 // Get current value of completion state and do nothing if it's same as
474 // the possible result of this change. If the change is to COMPLETE and the
475 // current value is one of the COMPLETE_xx subtypes, ignore that as well
0d5d12bd 476 $current = $this->get_data($cm, false, $userid);
477 if ($possibleresult == $current->completionstate ||
478 ($possibleresult == COMPLETION_COMPLETE &&
479 ($current->completionstate == COMPLETION_COMPLETE_PASS ||
480 $current->completionstate == COMPLETION_COMPLETE_FAIL))) {
4e781c7b 481 return;
482 }
0d5d12bd 483
484 if ($cm->completion == COMPLETION_TRACKING_MANUAL) {
4e781c7b 485 // For manual tracking we set the result directly
486 switch($possibleresult) {
487 case COMPLETION_COMPLETE:
488 case COMPLETION_INCOMPLETE:
0d5d12bd 489 $newstate = $possibleresult;
4e781c7b 490 break;
491 default:
492 $this->internal_systemerror("Unexpected manual completion state for {$cm->id}: $possibleresult");
493 }
d7d87535 494
4e781c7b 495 } else {
496 // Automatic tracking; get new state
0d5d12bd 497 $newstate = $this->internal_get_state($cm, $userid, $current);
4e781c7b 498 }
0d5d12bd 499
4e781c7b 500 // If changed, update
0d5d12bd 501 if ($newstate != $current->completionstate) {
502 $current->completionstate = $newstate;
503 $current->timemodified = time();
504 $this->internal_set_data($cm, $current);
4e781c7b 505 }
506 }
0d5d12bd 507
4e781c7b 508 /**
509 * Calculates the completion state for an activity and user.
4e781c7b 510 *
09639ded 511 * Internal function. Not private, so we can unit-test it.
512 *
513 * @global object
514 * @global object
515 * @global object
516 * @uses COMPLETION_VIEW_REQUIRED
517 * @uses COMPLETION_NOT_VIEWED
518 * @uses COMPLETION_INCOMPLETE
519 * @uses FEATURE_COMPLETION_HAS_RULES
520 * @uses COMPLETION_COMPLETE
521 * @uses COMPLETION_AND
4e781c7b 522 * @param object $cm Activity
523 * @param int $userid ID of user
524 * @param object $current Previous completion information from database
09639ded 525 * @return mixed
4e781c7b 526 */
0d5d12bd 527 function internal_get_state($cm, $userid, $current) {
7a7dbd77 528 global $USER, $DB, $CFG;
d7d87535 529
530 // Get user ID
0d5d12bd 531 if (!$userid) {
532 $userid = $USER->id;
4e781c7b 533 }
0d5d12bd 534
4e781c7b 535 // Check viewed
0d5d12bd 536 if ($cm->completionview == COMPLETION_VIEW_REQUIRED &&
537 $current->viewed == COMPLETION_NOT_VIEWED) {
538
4e781c7b 539 return COMPLETION_INCOMPLETE;
540 }
0d5d12bd 541
4e781c7b 542 // Modname hopefully is provided in $cm but just in case it isn't, let's grab it
0d5d12bd 543 if (!isset($cm->modname)) {
544 $cm->modname = $DB->get_field('modules', 'name', array('id'=>$cm->module));
4e781c7b 545 }
0d5d12bd 546
547 $newstate = COMPLETION_COMPLETE;
548
4e781c7b 549 // Check grade
0d5d12bd 550 if (!is_null($cm->completiongradeitemnumber)) {
7a7dbd77 551 require_once($CFG->libdir.'/gradelib.php');
0d5d12bd 552 $item = grade_item::fetch(array('courseid'=>$cm->course, 'itemtype'=>'mod',
553 'itemmodule'=>$cm->modname, 'iteminstance'=>$cm->instance,
4e781c7b 554 'itemnumber'=>$cm->completiongradeitemnumber));
0d5d12bd 555 if ($item) {
4e781c7b 556 // Fetch 'grades' (will be one or none)
0d5d12bd 557 $grades = grade_grade::fetch_users_grades($item, array($userid), false);
558 if (empty($grades)) {
4e781c7b 559 // No grade for user
560 return COMPLETION_INCOMPLETE;
561 }
0d5d12bd 562 if (count($grades) > 1) {
4e781c7b 563 $this->internal_systemerror("Unexpected result: multiple grades for
564 item '{$item->id}', user '{$userid}'");
565 }
0d5d12bd 566 $newstate = $this->internal_get_grade_state($item, reset($grades));
567 if ($newstate == COMPLETION_INCOMPLETE) {
4e781c7b 568 return COMPLETION_INCOMPLETE;
569 }
d7d87535 570
4e781c7b 571 } else {
572 $this->internal_systemerror("Cannot find grade item for '{$cm->modname}'
573 cm '{$cm->id}' matching number '{$cm->completiongradeitemnumber}'");
574 }
575 }
0d5d12bd 576
577 if (plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_HAS_RULES)) {
578 $function = $cm->modname.'_get_completion_state';
579 if (!function_exists($function)) {
4e781c7b 580 $this->internal_systemerror("Module {$cm->modname} claims to support
581 FEATURE_COMPLETION_HAS_RULES but does not have required
582 {$cm->modname}_get_completion_state function");
583 }
0d5d12bd 584 if (!$function($this->course, $cm, $userid, COMPLETION_AND)) {
4e781c7b 585 return COMPLETION_INCOMPLETE;
586 }
587 }
0d5d12bd 588
4e781c7b 589 return $newstate;
0d5d12bd 590
4e781c7b 591 }
0d5d12bd 592
593
4e781c7b 594 /**
595 * Marks a module as viewed.
09639ded 596 *
4e781c7b 597 * Should be called whenever a module is 'viewed' (it is up to the module how to
598 * determine that). Has no effect if viewing is not set as a completion condition.
599 *
6553cda7 600 * Note that this function must be called before you print the page header because
601 * it is possible that the navigation block may depend on it. If you call it after
602 * printing the header, it shows a developer debug warning.
09639ded 603 * @uses COMPLETION_VIEW_NOT_REQUIRED
604 * @uses COMPLETION_VIEWED
605 * @uses COMPLETION_COMPLETE
4e781c7b 606 * @param object $cm Activity
607 * @param int $userid User ID or 0 (default) for current user
09639ded 608 * @return void
4e781c7b 609 */
0d5d12bd 610 public function set_module_viewed($cm, $userid=0) {
1cec45f1 611 global $PAGE, $UNITTEST;
612 if ($PAGE->headerprinted && empty($UNITTEST->running)) {
6553cda7 613 debugging('set_module_viewed must be called before header is printed',
614 DEBUG_DEVELOPER);
615 }
4e781c7b 616 // Don't do anything if view condition is not turned on
0d5d12bd 617 if ($cm->completionview == COMPLETION_VIEW_NOT_REQUIRED || !$this->is_enabled($cm)) {
4e781c7b 618 return;
619 }
620 // Get current completion state
0d5d12bd 621 $data = $this->get_data($cm, $userid);
4e781c7b 622 // If we already viewed it, don't do anything
0d5d12bd 623 if ($data->viewed == COMPLETION_VIEWED) {
4e781c7b 624 return;
625 }
626 // OK, change state, save it, and update completion
0d5d12bd 627 $data->viewed = COMPLETION_VIEWED;
628 $this->internal_set_data($cm, $data);
629 $this->update_state($cm, COMPLETION_COMPLETE, $userid);
4e781c7b 630 }
0d5d12bd 631
4e781c7b 632 /**
633 * Determines how much completion data exists for an activity. This is used when
634 * deciding whether completion information should be 'locked' in the module
635 * editing form.
636 *
09639ded 637 * @global object
4e781c7b 638 * @param object $cm Activity
639 * @return int The number of users who have completion data stored for this
0d5d12bd 640 * activity, 0 if none
4e781c7b 641 */
642 public function count_user_data($cm) {
2be4d090 643 global $DB;
0d5d12bd 644
4e781c7b 645 return $DB->get_field_sql("
646 SELECT
647 COUNT(1)
648 FROM
49f6e5f4 649 {course_modules_completion}
4e781c7b 650 WHERE
0d5d12bd 651 coursemoduleid=? AND completionstate<>0", array($cm->id));
4e781c7b 652 }
0d5d12bd 653
2be4d090
MD
654 /**
655 * Determines how much course completion data exists for a course. This is used when
656 * deciding whether completion information should be 'locked' in the completion
657 * settings form and activity completion settings.
658 *
659 * @global object
660 * @param int $user_id Optionally only get course completion data for a single user
661 * @return int The number of users who have completion data stored for this
662 * course, 0 if none
663 */
664 public function count_course_user_data($user_id = null) {
665 global $DB;
666
667 $sql = '
668 SELECT
669 COUNT(1)
670 FROM
671 {course_completion_crit_compl}
672 WHERE
673 course = ?
674 ';
675
676 $params = array($this->course_id);
677
678 // Limit data to a single user if an ID is supplied
679 if ($user_id) {
680 $sql .= ' AND userid = ?';
681 $params[] = $user_id;
682 }
683
684 return $DB->get_field_sql($sql, $params);
685 }
686
687 /**
688 * Check if this course's completion criteria should be locked
689 *
690 * @return boolean
691 */
692 public function is_course_locked() {
693 return (bool) $this->count_course_user_data();
694 }
695
696 /**
697 * Deletes all course completion completion data.
698 *
699 * Intended to be used when unlocking completion criteria settings.
700 *
701 * @global object
702 * @return void
703 */
704 public function delete_course_completion_data() {
705 global $DB;
706
707 $DB->delete_records('course_completions', array('course' => $this->course_id));
708 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id));
709 }
710
4e781c7b 711 /**
0d5d12bd 712 * Deletes completion state related to an activity for all users.
117bd748 713 *
4e781c7b 714 * Intended for use only when the activity itself is deleted.
715 *
09639ded 716 * @global object
717 * @global object
4e781c7b 718 * @param object $cm Activity
719 */
0d5d12bd 720 public function delete_all_state($cm) {
721 global $SESSION, $DB;
722
4e781c7b 723 // Delete from database
0d5d12bd 724 $DB->delete_records('course_modules_completion', array('coursemoduleid'=>$cm->id));
725
4e781c7b 726 // Erase cache data for current user if applicable
0d5d12bd 727 if (isset($SESSION->completioncache) &&
728 array_key_exists($cm->course, $SESSION->completioncache) &&
729 array_key_exists($cm->id, $SESSION->completioncache[$cm->course])) {
730
4e781c7b 731 unset($SESSION->completioncache[$cm->course][$cm->id]);
732 }
2be4d090
MD
733
734 // Check if there is an associated course completion criteria
735 $criteria = $this->get_criteria(COMPLETION_CRITERIA_TYPE_ACTIVITY);
736 $acriteria = false;
737 foreach ($criteria as $criterion) {
738 if ($criterion->moduleinstance == $cm->id) {
739 $acriteria = $criterion;
740 break;
741 }
742 }
743
744 if ($acriteria) {
745 // Delete all criteria completions relating to this activity
746 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id, 'criteriaid' => $acriteria->id));
747 $DB->delete_records('course_completions', array('course' => $this->course_id));
748 }
4e781c7b 749 }
0d5d12bd 750
4e781c7b 751 /**
752 * Recalculates completion state related to an activity for all users.
117bd748 753 *
4e781c7b 754 * Intended for use if completion conditions change. (This should be avoided
755 * as it may cause some things to become incomplete when they were previously
756 * complete, with the effect - for example - of hiding a later activity that
757 * was previously available.)
117bd748 758 *
0d5d12bd 759 * Resetting state of manual tickbox has same result as deleting state for
81f64ed3 760 * it.
09639ded 761 *
762 * @global object
763 * @uses COMPLETION_TRACKING_MANUAL
764 * @uses COMPLETION_UNKNOWN
4e781c7b 765 * @param object $cm Activity
766 */
767 public function reset_all_state($cm) {
d7d87535 768 global $DB;
769
0d5d12bd 770 if ($cm->completion == COMPLETION_TRACKING_MANUAL) {
81f64ed3 771 $this->delete_all_state($cm);
772 return;
773 }
4e781c7b 774 // Get current list of users with completion state
0d5d12bd 775 $rs = $DB->get_recordset('course_modules_completion', array('coursemoduleid'=>$cm->id), '', 'userid');
776 $keepusers = array();
777 foreach ($rs as $rec) {
778 $keepusers[] = $rec->userid;
4e781c7b 779 }
780 $rs->close();
0d5d12bd 781
4e781c7b 782 // Delete all existing state [also clears session cache for current user]
783 $this->delete_all_state($cm);
0d5d12bd 784
785 // Merge this with list of planned users (according to roles)
24a3b341 786 $trackedusers = $this->get_tracked_users();
0d5d12bd 787 foreach ($trackedusers as $trackeduser) {
788 $keepusers[] = $trackeduser->id;
789 }
790 $keepusers = array_unique($keepusers);
791
4e781c7b 792 // Recalculate state for each kept user
0d5d12bd 793 foreach ($keepusers as $keepuser) {
794 $this->update_state($cm, COMPLETION_UNKNOWN, $keepuser);
4e781c7b 795 }
796 }
0d5d12bd 797
4e781c7b 798 /**
799 * Obtains completion data for a particular activity and user (from the
800 * session cache if available, or by SQL query)
801 *
09639ded 802 * @global object
803 * @global object
804 * @global object
805 * @global object
806 * @uses COMPLETION_CACHE_EXPIRY
82bd6a5e 807 * @param object $cm Activity; only required field is ->id
4e781c7b 808 * @param bool $wholecourse If true (default false) then, when necessary to
809 * fill the cache, retrieves information from the entire course not just for
810 * this one activity
811 * @param int $userid User ID or 0 (default) for current user
117bd748
PS
812 * @param array $modinfo Supply the value here - this is used for unit
813 * testing and so that it can be called recursively from within
82bd6a5e 814 * get_fast_modinfo. (Needs only list of all CMs with IDs.)
815 * Otherwise the method calls get_fast_modinfo itself.
4e781c7b 816 * @return object Completion data (record from course_modules_completion)
4e781c7b 817 */
0d5d12bd 818 public function get_data($cm, $wholecourse=false, $userid=0, $modinfo=null) {
0d5d12bd 819 global $USER, $CFG, $SESSION, $DB;
d7d87535 820
821 // Get user ID
0d5d12bd 822 if (!$userid) {
823 $userid = $USER->id;
4e781c7b 824 }
0d5d12bd 825
4e781c7b 826 // Is this the current user?
0d5d12bd 827 $currentuser = $userid==$USER->id;
828
2be4d090 829 if ($currentuser && is_object($SESSION)) {
0d5d12bd 830 // Make sure cache is present and is for current user (loginas
49f6e5f4 831 // changes this)
0d5d12bd 832 if (!isset($SESSION->completioncache) || $SESSION->completioncacheuserid!=$USER->id) {
833 $SESSION->completioncache = array();
834 $SESSION->completioncacheuserid = $USER->id;
4e781c7b 835 }
836 // Expire any old data from cache
0d5d12bd 837 foreach ($SESSION->completioncache as $courseid=>$activities) {
838 if (empty($activities['updated']) || $activities['updated'] < time()-COMPLETION_CACHE_EXPIRY) {
4e781c7b 839 unset($SESSION->completioncache[$courseid]);
840 }
841 }
842 // See if requested data is present, if so use cache to get it
0d5d12bd 843 if (isset($SESSION->completioncache) &&
844 array_key_exists($this->course->id, $SESSION->completioncache) &&
845 array_key_exists($cm->id, $SESSION->completioncache[$this->course->id])) {
846 return $SESSION->completioncache[$this->course->id][$cm->id];
4e781c7b 847 }
848 }
0d5d12bd 849
4e781c7b 850 // Not there, get via SQL
0d5d12bd 851 if ($currentuser && $wholecourse) {
4e781c7b 852 // Get whole course data for cache
0d5d12bd 853 $alldatabycmc = $DB->get_records_sql("
4e781c7b 854 SELECT
855 cmc.*
856 FROM
49f6e5f4 857 {course_modules} cm
858 INNER JOIN {course_modules_completion} cmc ON cmc.coursemoduleid=cm.id
0d5d12bd 859 WHERE
860 cm.course=? AND cmc.userid=?", array($this->course->id, $userid));
861
4e781c7b 862 // Reindex by cm id
0d5d12bd 863 $alldata = array();
864 if ($alldatabycmc) {
865 foreach ($alldatabycmc as $data) {
866 $alldata[$data->coursemoduleid] = $data;
4e781c7b 867 }
868 }
0d5d12bd 869
4e781c7b 870 // Get the module info and build up condition info for each one
0d5d12bd 871 if (empty($modinfo)) {
872 $modinfo = get_fast_modinfo($this->course, $userid);
4e781c7b 873 }
0d5d12bd 874 foreach ($modinfo->cms as $othercm) {
875 if (array_key_exists($othercm->id, $alldata)) {
876 $data = $alldata[$othercm->id];
4e781c7b 877 } else {
878 // Row not present counts as 'not complete'
0d5d12bd 879 $data = new StdClass;
880 $data->id = 0;
881 $data->coursemoduleid = $othercm->id;
882 $data->userid = $userid;
883 $data->completionstate = 0;
884 $data->viewed = 0;
885 $data->timemodified = 0;
4e781c7b 886 }
0d5d12bd 887 $SESSION->completioncache[$this->course->id][$othercm->id] = $data;
4e781c7b 888 }
0d5d12bd 889 $SESSION->completioncache[$this->course->id]['updated'] = time();
890
891 if (!isset($SESSION->completioncache[$this->course->id][$cm->id])) {
4e781c7b 892 $this->internal_systemerror("Unexpected error: course-module {$cm->id} could not be found on course {$this->course->id}");
893 }
894 return $SESSION->completioncache[$this->course->id][$cm->id];
d7d87535 895
4e781c7b 896 } else {
897 // Get single record
0d5d12bd 898 $data = $DB->get_record('course_modules_completion', array('coursemoduleid'=>$cm->id, 'userid'=>$userid));
899 if ($data == false) {
4e781c7b 900 // Row not present counts as 'not complete'
0d5d12bd 901 $data = new StdClass;
902 $data->id = 0;
903 $data->coursemoduleid = $cm->id;
904 $data->userid = $userid;
905 $data->completionstate = 0;
906 $data->viewed = 0;
907 $data->timemodified = 0;
4e781c7b 908 }
0d5d12bd 909
4e781c7b 910 // Put in cache
0d5d12bd 911 if ($currentuser) {
912 $SESSION->completioncache[$this->course->id][$cm->id] = $data;
4e781c7b 913 // For single updates, only set date if it was empty before
0d5d12bd 914 if (empty($SESSION->completioncache[$this->course->id]['updated'])) {
915 $SESSION->completioncache[$this->course->id]['updated'] = time();
4e781c7b 916 }
917 }
918 }
0d5d12bd 919
4e781c7b 920 return $data;
921 }
0d5d12bd 922
4e781c7b 923 /**
0d5d12bd 924 * Updates completion data for a particular coursemodule and user (user is
4e781c7b 925 * determined from $data).
117bd748 926 *
4e781c7b 927 * (Internal function. Not private, so we can unit-test it.)
0d5d12bd 928 *
09639ded 929 * @global object
930 * @global object
931 * @global object
4e781c7b 932 * @param object $cm Activity
933 * @param object $data Data about completion for that user
934 */
0d5d12bd 935 function internal_set_data($cm, $data) {
936 global $USER, $SESSION, $DB;
d7d87535 937
a854bca3 938 $transaction = $DB->start_delegated_transaction();
939 if (!$data->id) {
940 // Check there isn't really a row
941 $data->id = $DB->get_field('course_modules_completion', 'id',
942 array('coursemoduleid'=>$data->coursemoduleid, 'userid'=>$data->userid));
943 }
944 if (!$data->id) {
4e781c7b 945 // Didn't exist before, needs creating
0d5d12bd 946 $data->id = $DB->insert_record('course_modules_completion', $data);
a854bca3 947 } else {
948 // Has real (nonzero) id meaning that a database row exists, update
949 $DB->update_record('course_modules_completion', $data);
4e781c7b 950 }
a854bca3 951 $transaction->allow_commit();
d7d87535 952
0d5d12bd 953 if ($data->userid == $USER->id) {
954 $SESSION->completioncache[$cm->course][$cm->id] = $data;
6553cda7 955 $reset = 'reset';
956 get_fast_modinfo($reset);
4e781c7b 957 }
958 }
0d5d12bd 959
4e781c7b 960 /**
0d5d12bd 961 * Obtains a list of activities for which completion is enabled on the
4e781c7b 962 * course. The list is ordered by the section order of those activities.
09639ded 963 *
964 * @global object
965 * @uses COMPLETION_TRACKING_NONE
0d5d12bd 966 * @param array $modinfo For unit testing only, supply the value
4e781c7b 967 * here. Otherwise the method calls get_fast_modinfo
968 * @return array Array from $cmid => $cm of all activities with completion enabled,
969 * empty array if none
970 */
971 public function get_activities($modinfo=null) {
972 global $DB;
0d5d12bd 973
4e781c7b 974 // Obtain those activities which have completion turned on
0d5d12bd 975 $withcompletion = $DB->get_records_select('course_modules', 'course='.$this->course->id.
4e781c7b 976 ' AND completion<>'.COMPLETION_TRACKING_NONE);
2be4d090 977 if (!$withcompletion) {
4e781c7b 978 return array();
979 }
0d5d12bd 980
4e781c7b 981 // Use modinfo to get section order and also add in names
0d5d12bd 982 if (empty($modinfo)) {
983 $modinfo = get_fast_modinfo($this->course);
984 }
985 $result = array();
986 foreach ($modinfo->sections as $sectioncms) {
987 foreach ($sectioncms as $cmid) {
988 if (array_key_exists($cmid, $withcompletion)) {
989 $result[$cmid] = $withcompletion[$cmid];
990 $result[$cmid]->modname = $modinfo->cms[$cmid]->modname;
991 $result[$cmid]->name = $modinfo->cms[$cmid]->name;
4e781c7b 992 }
993 }
994 }
0d5d12bd 995
4e781c7b 996 return $result;
997 }
0d5d12bd 998
24a3b341 999
4e781c7b 1000 /**
24a3b341
AB
1001 * Checks to see if the userid supplied has a tracked role in
1002 * this course
09639ded 1003 *
24a3b341
AB
1004 * @param $userid User id
1005 * @return bool
4e781c7b 1006 */
24a3b341
AB
1007 function is_tracked_user($userid) {
1008 global $DB;
1009
5642a8e5
AB
1010 $tracked = $this->generate_tracked_user_sql();
1011
24a3b341 1012 $sql = "SELECT u.id ";
5642a8e5 1013 $sql .= $tracked->sql;
c4a88609 1014 $sql .= ' AND u.id = :userid';
5642a8e5
AB
1015
1016 $params = $tracked->data;
c4a88609 1017 $params['userid'] = (int)$userid;
5642a8e5 1018 return $DB->record_exists_sql($sql, $params);
24a3b341
AB
1019 }
1020
1021
1022 /**
1023 * Return number of users whose progress is tracked in this course
1024 *
1025 * Optionally supply a search's where clause, or a group id
1026 *
5642a8e5
AB
1027 * @param string $where Where clause sql
1028 * @param array $where_params Where clause params
24a3b341
AB
1029 * @param int $groupid Group id
1030 * @return int
1031 */
5642a8e5 1032 function get_num_tracked_users($where = '', $where_params = array(), $groupid = 0) {
24a3b341
AB
1033 global $DB;
1034
5642a8e5
AB
1035 $tracked = $this->generate_tracked_user_sql($groupid);
1036
24a3b341 1037 $sql = "SELECT COUNT(u.id) ";
5642a8e5 1038 $sql .= $tracked->sql;
24a3b341
AB
1039
1040 if ($where) {
1041 $sql .= " AND $where";
1042 }
1043
5642a8e5
AB
1044 $params = array_merge($tracked->data, $where_params);
1045 return $DB->count_records_sql($sql, $params);
24a3b341
AB
1046 }
1047
1048
1049 /**
1050 * Return array of users whose progress is tracked in this course
1051 *
1052 * Optionally supply a search's where caluse, group id, sorting, paging
1053 *
5642a8e5
AB
1054 * @param string $where Where clause sql (optional)
1055 * @param array $where_params Where clause params (optional)
24a3b341
AB
1056 * @param integer $groupid Group ID to restrict to (optional)
1057 * @param string $sort Order by clause (optional)
1058 * @param integer $limitfrom Result start (optional)
1059 * @param integer $limitnum Result max size (optional)
24e14bc7 1060 * @param context $extracontext If set, includes extra user information fields
1061 * as appropriate to display for current user in this context
24a3b341
AB
1062 * @return array
1063 */
5642a8e5 1064 function get_tracked_users($where = '', $where_params = array(), $groupid = 0,
24e14bc7 1065 $sort = '', $limitfrom = '', $limitnum = '', context $extracontext = null) {
24a3b341
AB
1066
1067 global $DB;
1068
5642a8e5
AB
1069 $tracked = $this->generate_tracked_user_sql($groupid);
1070 $params = $tracked->data;
1071
24a3b341
AB
1072 $sql = "
1073 SELECT
1074 u.id,
1075 u.firstname,
1076 u.lastname,
1077 u.idnumber
1078 ";
24e14bc7 1079 if ($extracontext) {
1080 $sql .= get_extra_user_fields_sql($extracontext, 'u', '', array('idnumber'));
1081 }
24a3b341 1082
5642a8e5 1083 $sql .= $tracked->sql;
24a3b341
AB
1084
1085 if ($where) {
1086 $sql .= " AND $where";
5642a8e5 1087 $params = array_merge($params, $where_params);
24a3b341
AB
1088 }
1089
1090 if ($sort) {
1091 $sql .= " ORDER BY $sort";
1092 }
1093
5642a8e5 1094 $users = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
24a3b341
AB
1095 return $users ? $users : array(); // In case it returns false
1096 }
1097
1098
1099 /**
1100 * Generate the SQL for finding tracked users in this course
1101 *
5642a8e5
AB
1102 * Returns an object containing the sql fragment and an array of
1103 * bound data params.
24a3b341
AB
1104 *
1105 * @param integer $groupid
5642a8e5 1106 * @return object
24a3b341
AB
1107 */
1108 function generate_tracked_user_sql($groupid = 0) {
1109 global $CFG;
d7d87535 1110
5642a8e5
AB
1111 $return = new stdClass();
1112 $return->sql = '';
1113 $return->data = array();
1114
1c6ed505 1115 if (!empty($CFG->gradebookroles)) {
1116 $roles = ' AND ra.roleid IN ('.$CFG->gradebookroles.')';
4e781c7b 1117 } else {
1118 // This causes it to default to everyone (if there is no student role)
24a3b341
AB
1119 $roles = '';
1120 }
1121
1122 // Build context sql
1123 $context = get_context_instance(CONTEXT_COURSE, $this->course->id);
1124 $parentcontexts = substr($context->path, 1); // kill leading slash
1125 $parentcontexts = str_replace('/', ',', $parentcontexts);
1126 if ($parentcontexts !== '') {
1127 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
4e781c7b 1128 }
24a3b341
AB
1129
1130 $groupjoin = '';
1131 $groupselect = '';
1132 if ($groupid) {
1133 $groupjoin = "JOIN {groups_members} gm
1134 ON gm.userid = u.id";
5642a8e5
AB
1135 $groupselect = " AND gm.groupid = :groupid ";
1136
1137 $return->data['groupid'] = $groupid;
24a3b341
AB
1138 }
1139
5642a8e5 1140 $return->sql = "
24a3b341
AB
1141 FROM
1142 {user} u
1143 INNER JOIN
1144 {role_assignments} ra
1145 ON ra.userid = u.id
1146 INNER JOIN
1147 {role} r
1148 ON r.id = ra.roleid
1149 INNER JOIN
1150 {user_enrolments} ue
1151 ON ue.userid = u.id
1152 INNER JOIN
1153 {enrol} e
1154 ON e.id = ue.enrolid
1155 INNER JOIN
1156 {course} c
1157 ON c.id = e.courseid
1158 $groupjoin
1159 WHERE
5642a8e5
AB
1160 (ra.contextid = :contextid $parentcontexts)
1161 AND c.id = :courseid
24a3b341
AB
1162 AND ue.status = 0
1163 AND e.status = 0
5642a8e5
AB
1164 AND ue.timestart < :now1
1165 AND (ue.timeend > :now2 OR ue.timeend = 0)
24a3b341
AB
1166 $groupselect
1167 $roles
1168 ";
1169
5642a8e5
AB
1170 $now = time();
1171 $return->data['now1'] = $now;
1172 $return->data['now2'] = $now;
1173 $return->data['contextid'] = $context->id;
1174 $return->data['courseid'] = $this->course->id;
1175
1176 return $return;
4e781c7b 1177 }
0d5d12bd 1178
4e781c7b 1179 /**
1180 * Obtains progress information across a course for all users on that course, or
1181 * for all users in a specific group. Intended for use when displaying progress.
117bd748 1182 *
4e781c7b 1183 * This includes only users who, in course context, have one of the roles for
1c6ed505 1184 * which progress is tracked (the gradebookroles admin option) and are enrolled in course.
117bd748 1185 *
4e781c7b 1186 * Users are included (in the first array) even if they do not have
1187 * completion progress for any course-module.
1188 *
09639ded 1189 * @global object
1190 * @global object
4e781c7b 1191 * @param bool $sortfirstname If true, sort by first name, otherwise sort by
1192 * last name
5642a8e5
AB
1193 * @param string $where Where clause sql (optional)
1194 * @param array $where_params Where clause params (optional)
4e781c7b 1195 * @param int $groupid Group ID or 0 (default)/false for all groups
24a3b341
AB
1196 * @param int $pagesize Number of users to actually return (optional)
1197 * @param int $start User to start at if paging (optional)
24e14bc7 1198 * @param context $extracontext If set, includes extra user information fields
1199 * as appropriate to display for current user in this context
35da0e87 1200 * @return Object with ->total and ->start (same as $start) and ->users;
1201 * an array of user objects (like mdl_user id, firstname, lastname)
4e781c7b 1202 * containing an additional ->progress array of coursemoduleid => completionstate
1203 */
5642a8e5 1204 public function get_progress_all($where = '', $where_params = array(), $groupid = 0,
24e14bc7 1205 $sort = '', $pagesize = '', $start = '', context $extracontext = null) {
0d5d12bd 1206 global $CFG, $DB;
1207
4e781c7b 1208 // Get list of applicable users
24e14bc7 1209 $users = $this->get_tracked_users($where, $where_params, $groupid, $sort,
1210 $start, $pagesize, $extracontext);
0d5d12bd 1211
1212 // Get progress information for these users in groups of 1, 000 (if needed)
4e781c7b 1213 // to avoid making the SQL IN too long
24a3b341 1214 $results = array();
0d5d12bd 1215 $userids = array();
1216 foreach ($users as $user) {
1217 $userids[] = $user->id;
24a3b341
AB
1218 $results[$user->id] = $user;
1219 $results[$user->id]->progress = array();
0d5d12bd 1220 }
1221
1222 for($i=0; $i<count($userids); $i+=1000) {
1223 $blocksize = count($userids)-$i < 1000 ? count($userids)-$i : 1000;
1224
1225 list($insql, $params) = $DB->get_in_or_equal(array_slice($userids, $i, $blocksize));
1226 array_splice($params, 0, 0, array($this->course->id));
1227 $rs = $DB->get_recordset_sql("
24a3b341
AB
1228 SELECT
1229 cmc.*
1230 FROM
1231 {course_modules} cm
1232 INNER JOIN {course_modules_completion} cmc ON cm.id=cmc.coursemoduleid
1233 WHERE
1234 cm.course=? AND cmc.userid $insql
0d5d12bd 1235 ", $params);
0d5d12bd 1236 foreach ($rs as $progress) {
24a3b341
AB
1237 $progress = (object)$progress;
1238 $results[$progress->userid]->progress[$progress->coursemoduleid] = $progress;
4e781c7b 1239 }
1240 $rs->close();
1241 }
0d5d12bd 1242
24a3b341 1243 return $results;
4e781c7b 1244 }
0d5d12bd 1245
09639ded 1246 /**
c4893595
SM
1247 * Called by grade code to inform the completion system when a grade has
1248 * been changed. If the changed grade is used to determine completion for
1249 * the course-module, then the completion status will be updated.
09639ded 1250 *
1251 * @uses COMPLETION_TRACKING_MANUAL
1252 * @uses COMPLETION_INCOMPLETE
c4893595
SM
1253 * @param object $cm Course-module for item that owns grade
1254 * @param grade_item $item Grade item
09639ded 1255 * @param object $grade
1256 * @param bool $deleted
1257 * @return void
1258 */
91537a88 1259 public function inform_grade_changed($cm, $item, $grade, $deleted) {
ca6b2d68 1260 // Bail out now if completion is not enabled for course-module, it is enabled
1261 // but is set to manual, grade is not used to compute completion, or this
1262 // is a different numbered grade
0d5d12bd 1263 if (!$this->is_enabled($cm) ||
ca6b2d68 1264 $cm->completion == COMPLETION_TRACKING_MANUAL ||
4e781c7b 1265 is_null($cm->completiongradeitemnumber) ||
0d5d12bd 1266 $item->itemnumber != $cm->completiongradeitemnumber) {
4e781c7b 1267 return;
1268 }
0d5d12bd 1269
4e781c7b 1270 // What is the expected result based on this grade?
0d5d12bd 1271 if ($deleted) {
4e781c7b 1272 // Grade being deleted, so only change could be to make it incomplete
0d5d12bd 1273 $possibleresult = COMPLETION_INCOMPLETE;
4e781c7b 1274 } else {
0d5d12bd 1275 $possibleresult = $this->internal_get_grade_state($item, $grade);
4e781c7b 1276 }
fd546aaa 1277
4e781c7b 1278 // OK, let's update state based on this
0d5d12bd 1279 $this->update_state($cm, $possibleresult, $grade->userid);
4e781c7b 1280 }
0d5d12bd 1281
4e781c7b 1282 /**
1283 * Calculates the completion state that would result from a graded item
1284 * (where grade-based completion is turned on) based on the actual grade
1285 * and settings.
117bd748 1286 *
09639ded 1287 * Internal function. Not private, so we can unit-test it.
4e781c7b 1288 *
09639ded 1289 * @uses COMPLETION_INCOMPLETE
1290 * @uses COMPLETION_COMPLETE_PASS
1291 * @uses COMPLETION_COMPLETE_FAIL
1292 * @uses COMPLETION_COMPLETE
1293 * @param object $item grade_item
1294 * @param object $grade grade_grade
4e781c7b 1295 * @return int Completion state e.g. COMPLETION_INCOMPLETE
1296 */
91537a88 1297 function internal_get_grade_state($item, $grade) {
0d5d12bd 1298 if (!$grade) {
4e781c7b 1299 return COMPLETION_INCOMPLETE;
1300 }
1301 // Conditions to show pass/fail:
1302 // a) Grade has pass mark (default is 0.00000 which is boolean true so be careful)
1303 // b) Grade is visible (neither hidden nor hidden-until)
0d5d12bd 1304 if ($item->gradepass && $item->gradepass > 0.000009 && !$item->hidden) {
4e781c7b 1305 // Use final grade if set otherwise raw grade
0d5d12bd 1306 $score = !is_null($grade->finalgrade) ? $grade->finalgrade : $grade->rawgrade;
1307
4e781c7b 1308 // We are displaying and tracking pass/fail
0d5d12bd 1309 if ($score >= $item->gradepass) {
4e781c7b 1310 return COMPLETION_COMPLETE_PASS;
1311 } else {
1312 return COMPLETION_COMPLETE_FAIL;
1313 }
1314 } else {
fd546aaa
SM
1315 // Not displaying pass/fail, so just if there is a grade
1316 if (!is_null($grade->finalgrade) || !is_null($grade->rawgrade)) {
1317 // Grade exists, so maybe complete now
1318 return COMPLETION_COMPLETE;
1319 } else {
1320 // Grade does not exist, so maybe incomplete now
1321 return COMPLETION_INCOMPLETE;
1322 }
4e781c7b 1323 }
1324 }
0d5d12bd 1325
4e781c7b 1326 /**
4e781c7b 1327 * This is to be used only for system errors (things that shouldn't happen)
1328 * and not user-level errors.
1329 *
09639ded 1330 * @global object
4e781c7b 1331 * @param string $error Error string (will not be displayed to user unless
1332 * debugging is enabled)
09639ded 1333 * @return void Throws moodle_exception Exception with the error string as debug info
4e781c7b 1334 */
1335 function internal_systemerror($error) {
1336 global $CFG;
82bd6a5e 1337 throw new moodle_exception('err_system','completion',
1338 $CFG->wwwroot.'/course/view.php?id='.$this->course->id,null,$error);
1339 }
d7d87535 1340
117bd748
PS
1341 /**
1342 * For testing only. Wipes information cached in user session.
09639ded 1343 *
1344 * @global object
1345 */
82bd6a5e 1346 static function wipe_session_cache() {
1347 global $SESSION;
1348 unset($SESSION->completioncache);
1349 unset($SESSION->completioncacheuserid);
4e781c7b 1350 }
1351}