lesson MDL-23525 committing this fix after its passed the tests in the bug/QA.
[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) {
4e781c7b 188 global $CFG;
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
4e781c7b 195 // Check course completion
0d5d12bd 196 if ($this->course->enablecompletion == COMPLETION_DISABLED) {
4e781c7b 197 return COMPLETION_DISABLED;
198 }
0d5d12bd 199
4e781c7b 200 // If there was no $cm and we got this far, then it's enabled
0d5d12bd 201 if (!$cm) {
4e781c7b 202 return COMPLETION_ENABLED;
203 }
0d5d12bd 204
4e781c7b 205 // Return course-module completion value
206 return $cm->completion;
207 }
0d5d12bd 208
e3568fde 209 /**
210 * Print the Your progress help icon if the completion tracking is enabled.
211 * @global object
212 * @return void
213 */
214 public function print_help_icon() {
aa9a6867 215 global $PAGE, $OUTPUT;
e3568fde 216 if ($this->is_enabled() && !$PAGE->user_is_editing() && isloggedin() && !isguestuser()) {
905b1de6 217 echo '<span id = "completionprogressid" class="completionprogress">'.get_string('yourprogress','completion').' ';
c8dcb793 218 echo $OUTPUT->help_icon('completionicons', 'completion');
e3568fde 219 echo '</span>';
220 }
221 }
2be4d090
MD
222
223 /**
224 * Get a course completion for a user
225 * @access public
226 * @param $user_id int User id
227 * @param $criteriatype int Specific criteria type to return
228 * @return false|completion_criteria_completion
229 */
230 public function get_completion($user_id, $criteriatype) {
231 $completions = $this->get_completions($user_id, $criteriatype);
232
233 if (empty($completions)) {
234 return false;
235 } elseif (count($completions) > 1) {
236 print_error('multipleselfcompletioncriteria', 'completion');
237 }
238
239 return $completions[0];
240 }
241
242 /**
243 * Get all course criteria's completion objects for a user
244 * @access public
245 * @param $user_id int User id
246 * @param $criteriatype int optional Specific criteria type to return
247 * @return array
248 */
249 public function get_completions($user_id, $criteriatype = null) {
250 $criterion = $this->get_criteria($criteriatype);
251
252 $completions = array();
253
254 foreach ($criterion as $criteria) {
255 $params = array(
256 'course' => $this->course_id,
257 'userid' => $user_id,
258 'criteriaid' => $criteria->id
259 );
260
261 $completion = new completion_criteria_completion($params);
262 $completion->attach_criteria($criteria);
263
264 $completions[] = $completion;
265 }
266
267 return $completions;
268 }
269
270 /**
271 * Get completion object for a user and a criteria
272 * @access public
273 * @param $user_id int User id
274 * @param $criteria completion_criteria Criteria object
275 * @return completion_criteria_completion
276 */
277 public function get_user_completion($user_id, $criteria) {
278 $params = array(
279 'criteriaid' => $criteria->id,
280 'userid' => $user_id
281 );
282
283 $completion = new completion_criteria_completion($params);
284 return $completion;
285 }
286
287 /**
288 * Check if course has completion criteria set
289 *
290 * @access public
291 * @return bool
292 */
293 public function has_criteria() {
294 $criteria = $this->get_criteria();
295
296 return (bool) count($criteria);
297 }
298
299
300 /**
301 * Get course completion criteria
302 * @access public
303 * @param $criteriatype int optional Specific criteria type to return
304 * @return void
305 */
306 public function get_criteria($criteriatype = null) {
307
308 // Fill cache if empty
309 if (!is_array($this->criteria)) {
310 global $DB;
311
312 $params = array(
313 'course' => $this->course->id
314 );
315
316 // Load criteria from database
317 $records = (array)$DB->get_records('course_completion_criteria', $params);
318
319 // Build array of criteria objects
320 $this->criteria = array();
321 foreach ($records as $record) {
322 $this->criteria[$record->id] = completion_criteria::factory($record);
323 }
324 }
325
326 // If after all criteria
327 if ($criteriatype === null) {
328 return $this->criteria;
329 }
330
331 // If we are only after a specific criteria type
332 $criteria = array();
333 foreach ($this->criteria as $criterion) {
334
335 if ($criterion->criteriatype != $criteriatype) {
336 continue;
337 }
338
339 $criteria[$criterion->id] = $criterion;
340 }
341
342 return $criteria;
343 }
344
345 /**
346 * Get aggregation method
347 * @access public
348 * @param $criteriatype int optional If none supplied, get overall aggregation method
349 * @return int
350 */
351 public function get_aggregation_method($criteriatype = null) {
352 $params = array(
353 'course' => $this->course_id,
354 'criteriatype' => $criteriatype
355 );
356
357 $aggregation = new completion_aggregation($params);
358
359 if (!$aggregation->id) {
360 $aggregation->method = COMPLETION_AGGREGATION_ALL;
361 }
362
363 return $aggregation->method;
364 }
365
366 /**
367 * Get incomplete course completion criteria
368 * @access public
369 * @return void
370 */
371 public function get_incomplete_criteria() {
372 $incomplete = array();
373
374 foreach ($this->get_criteria() as $criteria) {
375 if (!$criteria->is_complete()) {
376 $incomplete[] = $criteria;
377 }
378 }
379
380 return $incomplete;
381 }
382
383 /**
384 * Clear old course completion criteria
385 */
386 public function clear_criteria() {
387 global $DB;
388 $DB->delete_records('course_completion_criteria', array('course' => $this->course_id));
389 $DB->delete_records('course_completion_aggr_methd', array('course' => $this->course_id));
390
391 $this->delete_course_completion_data();
392 }
393
394 /**
395 * Has the supplied user completed this course
396 * @access public
397 * @param $user_id int User's id
398 * @return boolean
399 */
400 public function is_course_complete($user_id) {
401 $params = array(
402 'userid' => $user_id,
403 'course' => $this->course_id
404 );
405
406 $ccompletion = new completion_completion($params);
407 return $ccompletion->is_complete();
408 }
409
4e781c7b 410 /**
411 * Updates (if necessary) the completion state of activity $cm for the given
412 * user.
09639ded 413 *
4e781c7b 414 * For manual completion, this function is called when completion is toggled
415 * with $possibleresult set to the target state.
09639ded 416 *
4e781c7b 417 * For automatic completion, this function should be called every time a module
418 * does something which might influence a user's completion state. For example,
419 * if a forum provides options for marking itself 'completed' once a user makes
420 * N posts, this function should be called every time a user makes a new post.
421 * [After the post has been saved to the database]. When calling, you do not
422 * need to pass in the new completion state. Instead this function carries out
423 * completion calculation by checking grades and viewed state itself, and
424 * calling the involved module via modulename_get_completion_state() to check
425 * module-specific conditions.
426 *
09639ded 427 * @global object
428 * @global object
429 * @uses COMPLETION_COMPLETE
430 * @uses COMPLETION_INCOMPLETE
431 * @uses COMPLETION_COMPLETE_PASS
432 * @uses COMPLETION_COMPLETE_FAIL
433 * @uses COMPLETION_TRACKING_MANUAL
4e781c7b 434 * @param object $cm Course-module
435 * @param int $possibleresult Expected completion result. If the event that
436 * has just occurred (e.g. add post) can only result in making the activity
437 * complete when it wasn't before, use COMPLETION_COMPLETE. If the event that
438 * has just occurred (e.g. delete post) can only result in making the activity
439 * not complete when it was previously complete, use COMPLETION_INCOMPLETE.
440 * Otherwise use COMPLETION_UNKNOWN. Setting this value to something other than
441 * COMPLETION_UNKNOWN significantly improves performance because it will abandon
442 * processing early if the user's completion state already matches the expected
443 * result. For manual events, COMPLETION_COMPLETE or COMPLETION_INCOMPLETE
444 * must be used; these directly set the specified state.
445 * @param int $userid User ID to be updated. Default 0 = current user
09639ded 446 * @return void
4e781c7b 447 */
0d5d12bd 448 public function update_state($cm, $possibleresult=COMPLETION_UNKNOWN, $userid=0) {
449 global $USER, $SESSION;
d7d87535 450
0d5d12bd 451 // Do nothing if completion is not enabled for that activity
452 if (!$this->is_enabled($cm)) {
4e781c7b 453 return;
454 }
0d5d12bd 455
4e781c7b 456 // Get current value of completion state and do nothing if it's same as
457 // the possible result of this change. If the change is to COMPLETE and the
458 // current value is one of the COMPLETE_xx subtypes, ignore that as well
0d5d12bd 459 $current = $this->get_data($cm, false, $userid);
460 if ($possibleresult == $current->completionstate ||
461 ($possibleresult == COMPLETION_COMPLETE &&
462 ($current->completionstate == COMPLETION_COMPLETE_PASS ||
463 $current->completionstate == COMPLETION_COMPLETE_FAIL))) {
4e781c7b 464 return;
465 }
0d5d12bd 466
467 if ($cm->completion == COMPLETION_TRACKING_MANUAL) {
4e781c7b 468 // For manual tracking we set the result directly
469 switch($possibleresult) {
470 case COMPLETION_COMPLETE:
471 case COMPLETION_INCOMPLETE:
0d5d12bd 472 $newstate = $possibleresult;
4e781c7b 473 break;
474 default:
475 $this->internal_systemerror("Unexpected manual completion state for {$cm->id}: $possibleresult");
476 }
d7d87535 477
4e781c7b 478 } else {
479 // Automatic tracking; get new state
0d5d12bd 480 $newstate = $this->internal_get_state($cm, $userid, $current);
4e781c7b 481 }
0d5d12bd 482
4e781c7b 483 // If changed, update
0d5d12bd 484 if ($newstate != $current->completionstate) {
485 $current->completionstate = $newstate;
486 $current->timemodified = time();
487 $this->internal_set_data($cm, $current);
4e781c7b 488 }
489 }
0d5d12bd 490
4e781c7b 491 /**
492 * Calculates the completion state for an activity and user.
4e781c7b 493 *
09639ded 494 * Internal function. Not private, so we can unit-test it.
495 *
496 * @global object
497 * @global object
498 * @global object
499 * @uses COMPLETION_VIEW_REQUIRED
500 * @uses COMPLETION_NOT_VIEWED
501 * @uses COMPLETION_INCOMPLETE
502 * @uses FEATURE_COMPLETION_HAS_RULES
503 * @uses COMPLETION_COMPLETE
504 * @uses COMPLETION_AND
4e781c7b 505 * @param object $cm Activity
506 * @param int $userid ID of user
507 * @param object $current Previous completion information from database
09639ded 508 * @return mixed
4e781c7b 509 */
0d5d12bd 510 function internal_get_state($cm, $userid, $current) {
7a7dbd77 511 global $USER, $DB, $CFG;
d7d87535 512
513 // Get user ID
0d5d12bd 514 if (!$userid) {
515 $userid = $USER->id;
4e781c7b 516 }
0d5d12bd 517
4e781c7b 518 // Check viewed
0d5d12bd 519 if ($cm->completionview == COMPLETION_VIEW_REQUIRED &&
520 $current->viewed == COMPLETION_NOT_VIEWED) {
521
4e781c7b 522 return COMPLETION_INCOMPLETE;
523 }
0d5d12bd 524
4e781c7b 525 // Modname hopefully is provided in $cm but just in case it isn't, let's grab it
0d5d12bd 526 if (!isset($cm->modname)) {
527 $cm->modname = $DB->get_field('modules', 'name', array('id'=>$cm->module));
4e781c7b 528 }
0d5d12bd 529
530 $newstate = COMPLETION_COMPLETE;
531
4e781c7b 532 // Check grade
0d5d12bd 533 if (!is_null($cm->completiongradeitemnumber)) {
7a7dbd77 534 require_once($CFG->libdir.'/gradelib.php');
0d5d12bd 535 $item = grade_item::fetch(array('courseid'=>$cm->course, 'itemtype'=>'mod',
536 'itemmodule'=>$cm->modname, 'iteminstance'=>$cm->instance,
4e781c7b 537 'itemnumber'=>$cm->completiongradeitemnumber));
0d5d12bd 538 if ($item) {
4e781c7b 539 // Fetch 'grades' (will be one or none)
0d5d12bd 540 $grades = grade_grade::fetch_users_grades($item, array($userid), false);
541 if (empty($grades)) {
4e781c7b 542 // No grade for user
543 return COMPLETION_INCOMPLETE;
544 }
0d5d12bd 545 if (count($grades) > 1) {
4e781c7b 546 $this->internal_systemerror("Unexpected result: multiple grades for
547 item '{$item->id}', user '{$userid}'");
548 }
0d5d12bd 549 $newstate = $this->internal_get_grade_state($item, reset($grades));
550 if ($newstate == COMPLETION_INCOMPLETE) {
4e781c7b 551 return COMPLETION_INCOMPLETE;
552 }
d7d87535 553
4e781c7b 554 } else {
555 $this->internal_systemerror("Cannot find grade item for '{$cm->modname}'
556 cm '{$cm->id}' matching number '{$cm->completiongradeitemnumber}'");
557 }
558 }
0d5d12bd 559
560 if (plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_HAS_RULES)) {
561 $function = $cm->modname.'_get_completion_state';
562 if (!function_exists($function)) {
4e781c7b 563 $this->internal_systemerror("Module {$cm->modname} claims to support
564 FEATURE_COMPLETION_HAS_RULES but does not have required
565 {$cm->modname}_get_completion_state function");
566 }
0d5d12bd 567 if (!$function($this->course, $cm, $userid, COMPLETION_AND)) {
4e781c7b 568 return COMPLETION_INCOMPLETE;
569 }
570 }
0d5d12bd 571
4e781c7b 572 return $newstate;
0d5d12bd 573
4e781c7b 574 }
0d5d12bd 575
576
4e781c7b 577 /**
578 * Marks a module as viewed.
09639ded 579 *
4e781c7b 580 * Should be called whenever a module is 'viewed' (it is up to the module how to
581 * determine that). Has no effect if viewing is not set as a completion condition.
582 *
09639ded 583 * @uses COMPLETION_VIEW_NOT_REQUIRED
584 * @uses COMPLETION_VIEWED
585 * @uses COMPLETION_COMPLETE
4e781c7b 586 * @param object $cm Activity
587 * @param int $userid User ID or 0 (default) for current user
09639ded 588 * @return void
4e781c7b 589 */
0d5d12bd 590 public function set_module_viewed($cm, $userid=0) {
4e781c7b 591 // Don't do anything if view condition is not turned on
0d5d12bd 592 if ($cm->completionview == COMPLETION_VIEW_NOT_REQUIRED || !$this->is_enabled($cm)) {
4e781c7b 593 return;
594 }
595 // Get current completion state
0d5d12bd 596 $data = $this->get_data($cm, $userid);
4e781c7b 597 // If we already viewed it, don't do anything
0d5d12bd 598 if ($data->viewed == COMPLETION_VIEWED) {
4e781c7b 599 return;
600 }
601 // OK, change state, save it, and update completion
0d5d12bd 602 $data->viewed = COMPLETION_VIEWED;
603 $this->internal_set_data($cm, $data);
604 $this->update_state($cm, COMPLETION_COMPLETE, $userid);
4e781c7b 605 }
0d5d12bd 606
4e781c7b 607 /**
608 * Determines how much completion data exists for an activity. This is used when
609 * deciding whether completion information should be 'locked' in the module
610 * editing form.
611 *
09639ded 612 * @global object
4e781c7b 613 * @param object $cm Activity
614 * @return int The number of users who have completion data stored for this
0d5d12bd 615 * activity, 0 if none
4e781c7b 616 */
617 public function count_user_data($cm) {
2be4d090 618 global $DB;
0d5d12bd 619
4e781c7b 620 return $DB->get_field_sql("
621 SELECT
622 COUNT(1)
623 FROM
49f6e5f4 624 {course_modules_completion}
4e781c7b 625 WHERE
0d5d12bd 626 coursemoduleid=? AND completionstate<>0", array($cm->id));
4e781c7b 627 }
0d5d12bd 628
2be4d090
MD
629 /**
630 * Determines how much course completion data exists for a course. This is used when
631 * deciding whether completion information should be 'locked' in the completion
632 * settings form and activity completion settings.
633 *
634 * @global object
635 * @param int $user_id Optionally only get course completion data for a single user
636 * @return int The number of users who have completion data stored for this
637 * course, 0 if none
638 */
639 public function count_course_user_data($user_id = null) {
640 global $DB;
641
642 $sql = '
643 SELECT
644 COUNT(1)
645 FROM
646 {course_completion_crit_compl}
647 WHERE
648 course = ?
649 ';
650
651 $params = array($this->course_id);
652
653 // Limit data to a single user if an ID is supplied
654 if ($user_id) {
655 $sql .= ' AND userid = ?';
656 $params[] = $user_id;
657 }
658
659 return $DB->get_field_sql($sql, $params);
660 }
661
662 /**
663 * Check if this course's completion criteria should be locked
664 *
665 * @return boolean
666 */
667 public function is_course_locked() {
668 return (bool) $this->count_course_user_data();
669 }
670
671 /**
672 * Deletes all course completion completion data.
673 *
674 * Intended to be used when unlocking completion criteria settings.
675 *
676 * @global object
677 * @return void
678 */
679 public function delete_course_completion_data() {
680 global $DB;
681
682 $DB->delete_records('course_completions', array('course' => $this->course_id));
683 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id));
684 }
685
4e781c7b 686 /**
0d5d12bd 687 * Deletes completion state related to an activity for all users.
117bd748 688 *
4e781c7b 689 * Intended for use only when the activity itself is deleted.
690 *
09639ded 691 * @global object
692 * @global object
4e781c7b 693 * @param object $cm Activity
694 */
0d5d12bd 695 public function delete_all_state($cm) {
696 global $SESSION, $DB;
697
4e781c7b 698 // Delete from database
0d5d12bd 699 $DB->delete_records('course_modules_completion', array('coursemoduleid'=>$cm->id));
700
4e781c7b 701 // Erase cache data for current user if applicable
0d5d12bd 702 if (isset($SESSION->completioncache) &&
703 array_key_exists($cm->course, $SESSION->completioncache) &&
704 array_key_exists($cm->id, $SESSION->completioncache[$cm->course])) {
705
4e781c7b 706 unset($SESSION->completioncache[$cm->course][$cm->id]);
707 }
2be4d090
MD
708
709 // Check if there is an associated course completion criteria
710 $criteria = $this->get_criteria(COMPLETION_CRITERIA_TYPE_ACTIVITY);
711 $acriteria = false;
712 foreach ($criteria as $criterion) {
713 if ($criterion->moduleinstance == $cm->id) {
714 $acriteria = $criterion;
715 break;
716 }
717 }
718
719 if ($acriteria) {
720 // Delete all criteria completions relating to this activity
721 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id, 'criteriaid' => $acriteria->id));
722 $DB->delete_records('course_completions', array('course' => $this->course_id));
723 }
4e781c7b 724 }
0d5d12bd 725
4e781c7b 726 /**
727 * Recalculates completion state related to an activity for all users.
117bd748 728 *
4e781c7b 729 * Intended for use if completion conditions change. (This should be avoided
730 * as it may cause some things to become incomplete when they were previously
731 * complete, with the effect - for example - of hiding a later activity that
732 * was previously available.)
117bd748 733 *
0d5d12bd 734 * Resetting state of manual tickbox has same result as deleting state for
81f64ed3 735 * it.
09639ded 736 *
737 * @global object
738 * @uses COMPLETION_TRACKING_MANUAL
739 * @uses COMPLETION_UNKNOWN
4e781c7b 740 * @param object $cm Activity
741 */
742 public function reset_all_state($cm) {
d7d87535 743 global $DB;
744
0d5d12bd 745 if ($cm->completion == COMPLETION_TRACKING_MANUAL) {
81f64ed3 746 $this->delete_all_state($cm);
747 return;
748 }
4e781c7b 749 // Get current list of users with completion state
0d5d12bd 750 $rs = $DB->get_recordset('course_modules_completion', array('coursemoduleid'=>$cm->id), '', 'userid');
751 $keepusers = array();
752 foreach ($rs as $rec) {
753 $keepusers[] = $rec->userid;
4e781c7b 754 }
755 $rs->close();
0d5d12bd 756
4e781c7b 757 // Delete all existing state [also clears session cache for current user]
758 $this->delete_all_state($cm);
0d5d12bd 759
760 // Merge this with list of planned users (according to roles)
761 $trackedusers = $this->internal_get_tracked_users(false);
762 foreach ($trackedusers as $trackeduser) {
763 $keepusers[] = $trackeduser->id;
764 }
765 $keepusers = array_unique($keepusers);
766
4e781c7b 767 // Recalculate state for each kept user
0d5d12bd 768 foreach ($keepusers as $keepuser) {
769 $this->update_state($cm, COMPLETION_UNKNOWN, $keepuser);
4e781c7b 770 }
771 }
0d5d12bd 772
4e781c7b 773 /**
774 * Obtains completion data for a particular activity and user (from the
775 * session cache if available, or by SQL query)
776 *
09639ded 777 * @global object
778 * @global object
779 * @global object
780 * @global object
781 * @uses COMPLETION_CACHE_EXPIRY
82bd6a5e 782 * @param object $cm Activity; only required field is ->id
4e781c7b 783 * @param bool $wholecourse If true (default false) then, when necessary to
784 * fill the cache, retrieves information from the entire course not just for
785 * this one activity
786 * @param int $userid User ID or 0 (default) for current user
117bd748
PS
787 * @param array $modinfo Supply the value here - this is used for unit
788 * testing and so that it can be called recursively from within
82bd6a5e 789 * get_fast_modinfo. (Needs only list of all CMs with IDs.)
790 * Otherwise the method calls get_fast_modinfo itself.
4e781c7b 791 * @return object Completion data (record from course_modules_completion)
4e781c7b 792 */
0d5d12bd 793 public function get_data($cm, $wholecourse=false, $userid=0, $modinfo=null) {
0d5d12bd 794 global $USER, $CFG, $SESSION, $DB;
d7d87535 795
796 // Get user ID
0d5d12bd 797 if (!$userid) {
798 $userid = $USER->id;
4e781c7b 799 }
0d5d12bd 800
4e781c7b 801 // Is this the current user?
0d5d12bd 802 $currentuser = $userid==$USER->id;
803
2be4d090 804 if ($currentuser && is_object($SESSION)) {
0d5d12bd 805 // Make sure cache is present and is for current user (loginas
49f6e5f4 806 // changes this)
0d5d12bd 807 if (!isset($SESSION->completioncache) || $SESSION->completioncacheuserid!=$USER->id) {
808 $SESSION->completioncache = array();
809 $SESSION->completioncacheuserid = $USER->id;
4e781c7b 810 }
811 // Expire any old data from cache
0d5d12bd 812 foreach ($SESSION->completioncache as $courseid=>$activities) {
813 if (empty($activities['updated']) || $activities['updated'] < time()-COMPLETION_CACHE_EXPIRY) {
4e781c7b 814 unset($SESSION->completioncache[$courseid]);
815 }
816 }
817 // See if requested data is present, if so use cache to get it
0d5d12bd 818 if (isset($SESSION->completioncache) &&
819 array_key_exists($this->course->id, $SESSION->completioncache) &&
820 array_key_exists($cm->id, $SESSION->completioncache[$this->course->id])) {
821 return $SESSION->completioncache[$this->course->id][$cm->id];
4e781c7b 822 }
823 }
0d5d12bd 824
4e781c7b 825 // Not there, get via SQL
0d5d12bd 826 if ($currentuser && $wholecourse) {
4e781c7b 827 // Get whole course data for cache
0d5d12bd 828 $alldatabycmc = $DB->get_records_sql("
4e781c7b 829 SELECT
830 cmc.*
831 FROM
49f6e5f4 832 {course_modules} cm
833 INNER JOIN {course_modules_completion} cmc ON cmc.coursemoduleid=cm.id
0d5d12bd 834 WHERE
835 cm.course=? AND cmc.userid=?", array($this->course->id, $userid));
836
4e781c7b 837 // Reindex by cm id
0d5d12bd 838 $alldata = array();
839 if ($alldatabycmc) {
840 foreach ($alldatabycmc as $data) {
841 $alldata[$data->coursemoduleid] = $data;
4e781c7b 842 }
843 }
0d5d12bd 844
4e781c7b 845 // Get the module info and build up condition info for each one
0d5d12bd 846 if (empty($modinfo)) {
847 $modinfo = get_fast_modinfo($this->course, $userid);
4e781c7b 848 }
0d5d12bd 849 foreach ($modinfo->cms as $othercm) {
850 if (array_key_exists($othercm->id, $alldata)) {
851 $data = $alldata[$othercm->id];
4e781c7b 852 } else {
853 // Row not present counts as 'not complete'
0d5d12bd 854 $data = new StdClass;
855 $data->id = 0;
856 $data->coursemoduleid = $othercm->id;
857 $data->userid = $userid;
858 $data->completionstate = 0;
859 $data->viewed = 0;
860 $data->timemodified = 0;
4e781c7b 861 }
0d5d12bd 862 $SESSION->completioncache[$this->course->id][$othercm->id] = $data;
4e781c7b 863 }
0d5d12bd 864 $SESSION->completioncache[$this->course->id]['updated'] = time();
865
866 if (!isset($SESSION->completioncache[$this->course->id][$cm->id])) {
4e781c7b 867 $this->internal_systemerror("Unexpected error: course-module {$cm->id} could not be found on course {$this->course->id}");
868 }
869 return $SESSION->completioncache[$this->course->id][$cm->id];
d7d87535 870
4e781c7b 871 } else {
872 // Get single record
0d5d12bd 873 $data = $DB->get_record('course_modules_completion', array('coursemoduleid'=>$cm->id, 'userid'=>$userid));
874 if ($data == false) {
4e781c7b 875 // Row not present counts as 'not complete'
0d5d12bd 876 $data = new StdClass;
877 $data->id = 0;
878 $data->coursemoduleid = $cm->id;
879 $data->userid = $userid;
880 $data->completionstate = 0;
881 $data->viewed = 0;
882 $data->timemodified = 0;
4e781c7b 883 }
0d5d12bd 884
4e781c7b 885 // Put in cache
0d5d12bd 886 if ($currentuser) {
887 $SESSION->completioncache[$this->course->id][$cm->id] = $data;
4e781c7b 888 // For single updates, only set date if it was empty before
0d5d12bd 889 if (empty($SESSION->completioncache[$this->course->id]['updated'])) {
890 $SESSION->completioncache[$this->course->id]['updated'] = time();
4e781c7b 891 }
892 }
893 }
0d5d12bd 894
4e781c7b 895 return $data;
896 }
0d5d12bd 897
4e781c7b 898 /**
0d5d12bd 899 * Updates completion data for a particular coursemodule and user (user is
4e781c7b 900 * determined from $data).
117bd748 901 *
4e781c7b 902 * (Internal function. Not private, so we can unit-test it.)
0d5d12bd 903 *
09639ded 904 * @global object
905 * @global object
906 * @global object
4e781c7b 907 * @param object $cm Activity
908 * @param object $data Data about completion for that user
909 */
0d5d12bd 910 function internal_set_data($cm, $data) {
911 global $USER, $SESSION, $DB;
d7d87535 912
0d5d12bd 913 if ($data->id) {
4e781c7b 914 // Has real (nonzero) id meaning that a database row exists
0d5d12bd 915 $DB->update_record('course_modules_completion', $data);
916 } else {
4e781c7b 917 // Didn't exist before, needs creating
0d5d12bd 918 $data->id = $DB->insert_record('course_modules_completion', $data);
4e781c7b 919 }
d7d87535 920
0d5d12bd 921 if ($data->userid == $USER->id) {
922 $SESSION->completioncache[$cm->course][$cm->id] = $data;
4e781c7b 923 }
924 }
0d5d12bd 925
4e781c7b 926 /**
0d5d12bd 927 * Obtains a list of activities for which completion is enabled on the
4e781c7b 928 * course. The list is ordered by the section order of those activities.
09639ded 929 *
930 * @global object
931 * @uses COMPLETION_TRACKING_NONE
0d5d12bd 932 * @param array $modinfo For unit testing only, supply the value
4e781c7b 933 * here. Otherwise the method calls get_fast_modinfo
934 * @return array Array from $cmid => $cm of all activities with completion enabled,
935 * empty array if none
936 */
937 public function get_activities($modinfo=null) {
938 global $DB;
0d5d12bd 939
4e781c7b 940 // Obtain those activities which have completion turned on
0d5d12bd 941 $withcompletion = $DB->get_records_select('course_modules', 'course='.$this->course->id.
4e781c7b 942 ' AND completion<>'.COMPLETION_TRACKING_NONE);
2be4d090 943 if (!$withcompletion) {
4e781c7b 944 return array();
945 }
0d5d12bd 946
4e781c7b 947 // Use modinfo to get section order and also add in names
0d5d12bd 948 if (empty($modinfo)) {
949 $modinfo = get_fast_modinfo($this->course);
950 }
951 $result = array();
952 foreach ($modinfo->sections as $sectioncms) {
953 foreach ($sectioncms as $cmid) {
954 if (array_key_exists($cmid, $withcompletion)) {
955 $result[$cmid] = $withcompletion[$cmid];
956 $result[$cmid]->modname = $modinfo->cms[$cmid]->modname;
957 $result[$cmid]->name = $modinfo->cms[$cmid]->name;
4e781c7b 958 }
959 }
960 }
0d5d12bd 961
4e781c7b 962 return $result;
963 }
0d5d12bd 964
4e781c7b 965 /**
0d5d12bd 966 * Gets list of users in a course whose progress is tracked for display on the
4e781c7b 967 * progress report.
09639ded 968 *
969 * @global object
970 * @global object
971 * @uses CONTEXT_COURSE
2be4d090 972 * @param bool $sortfirstname Optional True to sort with firstname
4e781c7b 973 * @param int $groupid Optionally restrict to groupid
974 * @return array Array of user objects containing id, firstname, lastname (empty if none)
975 */
2be4d090 976 function internal_get_tracked_users($sortfirstname = false, $groupid = 0) {
0d5d12bd 977 global $CFG, $DB;
d7d87535 978
0d5d12bd 979 if (!empty($CFG->progresstrackedroles)) {
980 $roles = explode(', ', $CFG->progresstrackedroles);
4e781c7b 981 } else {
982 // This causes it to default to everyone (if there is no student role)
0d5d12bd 983 $roles = array();
4e781c7b 984 }
0d5d12bd 985 $users = get_role_users($roles, get_context_instance(CONTEXT_COURSE, $this->course->id), true,
986 'u.id, u.firstname, u.lastname, u.idnumber',
987 $sortfirstname ? 'u.firstname ASC' : 'u.lastname ASC', true, $groupid);
988 $users = $users ? $users : array(); // In case it returns false
4e781c7b 989 return $users;
990 }
0d5d12bd 991
4e781c7b 992 /**
993 * Obtains progress information across a course for all users on that course, or
994 * for all users in a specific group. Intended for use when displaying progress.
117bd748 995 *
4e781c7b 996 * This includes only users who, in course context, have one of the roles for
997 * which progress is tracked (the progresstrackedroles admin option).
117bd748 998 *
4e781c7b 999 * Users are included (in the first array) even if they do not have
1000 * completion progress for any course-module.
1001 *
09639ded 1002 * @global object
1003 * @global object
4e781c7b 1004 * @param bool $sortfirstname If true, sort by first name, otherwise sort by
1005 * last name
1006 * @param int $groupid Group ID or 0 (default)/false for all groups
35da0e87 1007 * @param int $pagesize Number of users to actually return (0 = unlimited)
1008 * @param int $start User to start at if paging (0 = first set)
1009 * @return Object with ->total and ->start (same as $start) and ->users;
1010 * an array of user objects (like mdl_user id, firstname, lastname)
4e781c7b 1011 * containing an additional ->progress array of coursemoduleid => completionstate
1012 */
35da0e87 1013 public function get_progress_all($sortfirstname=false, $groupid=0,
9b0e2d66 1014 $pagesize=0,$start=0) {
0d5d12bd 1015 global $CFG, $DB;
35da0e87 1016 $resultobject=new StdClass;
0d5d12bd 1017
4e781c7b 1018 // Get list of applicable users
0d5d12bd 1019 $users = $this->internal_get_tracked_users($sortfirstname, $groupid);
35da0e87 1020 $resultobject->start=$start;
1021 $resultobject->total=count($users);
002f56ef 1022 $users=array_slice($users,$start,$pagesize==0 ? count($users)-$start : $pagesize);
0d5d12bd 1023
1024 // Get progress information for these users in groups of 1, 000 (if needed)
4e781c7b 1025 // to avoid making the SQL IN too long
35da0e87 1026 $resultobject->users=array();
0d5d12bd 1027 $userids = array();
1028 foreach ($users as $user) {
1029 $userids[] = $user->id;
35da0e87 1030 $resultobject->users[$user->id]=$user;
82bd6a5e 1031 $resultobject->users[$user->id]->progress=array();
0d5d12bd 1032 }
1033
1034 for($i=0; $i<count($userids); $i+=1000) {
1035 $blocksize = count($userids)-$i < 1000 ? count($userids)-$i : 1000;
1036
1037 list($insql, $params) = $DB->get_in_or_equal(array_slice($userids, $i, $blocksize));
1038 array_splice($params, 0, 0, array($this->course->id));
1039 $rs = $DB->get_recordset_sql("
4e781c7b 1040SELECT
1041 cmc.*
1042FROM
49f6e5f4 1043 {course_modules} cm
1044 INNER JOIN {course_modules_completion} cmc ON cm.id=cmc.coursemoduleid
4e781c7b 1045WHERE
1046 cm.course=? AND cmc.userid $insql
0d5d12bd 1047 ", $params);
0d5d12bd 1048 foreach ($rs as $progress) {
35da0e87 1049 $resultobject->users[$progress->userid]->progress[$progress->coursemoduleid]=$progress;
4e781c7b 1050 }
1051 $rs->close();
1052 }
0d5d12bd 1053
35da0e87 1054 return $resultobject;
4e781c7b 1055 }
0d5d12bd 1056
09639ded 1057 /**
c4893595
SM
1058 * Called by grade code to inform the completion system when a grade has
1059 * been changed. If the changed grade is used to determine completion for
1060 * the course-module, then the completion status will be updated.
09639ded 1061 *
1062 * @uses COMPLETION_TRACKING_MANUAL
1063 * @uses COMPLETION_INCOMPLETE
c4893595
SM
1064 * @param object $cm Course-module for item that owns grade
1065 * @param grade_item $item Grade item
09639ded 1066 * @param object $grade
1067 * @param bool $deleted
1068 * @return void
1069 */
91537a88 1070 public function inform_grade_changed($cm, $item, $grade, $deleted) {
ca6b2d68 1071 // Bail out now if completion is not enabled for course-module, it is enabled
1072 // but is set to manual, grade is not used to compute completion, or this
1073 // is a different numbered grade
0d5d12bd 1074 if (!$this->is_enabled($cm) ||
ca6b2d68 1075 $cm->completion == COMPLETION_TRACKING_MANUAL ||
4e781c7b 1076 is_null($cm->completiongradeitemnumber) ||
0d5d12bd 1077 $item->itemnumber != $cm->completiongradeitemnumber) {
4e781c7b 1078 return;
1079 }
0d5d12bd 1080
4e781c7b 1081 // What is the expected result based on this grade?
0d5d12bd 1082 if ($deleted) {
4e781c7b 1083 // Grade being deleted, so only change could be to make it incomplete
0d5d12bd 1084 $possibleresult = COMPLETION_INCOMPLETE;
4e781c7b 1085 } else {
0d5d12bd 1086 $possibleresult = $this->internal_get_grade_state($item, $grade);
4e781c7b 1087 }
0d5d12bd 1088
4e781c7b 1089 // OK, let's update state based on this
0d5d12bd 1090 $this->update_state($cm, $possibleresult, $grade->userid);
4e781c7b 1091 }
0d5d12bd 1092
4e781c7b 1093 /**
1094 * Calculates the completion state that would result from a graded item
1095 * (where grade-based completion is turned on) based on the actual grade
1096 * and settings.
117bd748 1097 *
09639ded 1098 * Internal function. Not private, so we can unit-test it.
4e781c7b 1099 *
09639ded 1100 * @uses COMPLETION_INCOMPLETE
1101 * @uses COMPLETION_COMPLETE_PASS
1102 * @uses COMPLETION_COMPLETE_FAIL
1103 * @uses COMPLETION_COMPLETE
1104 * @param object $item grade_item
1105 * @param object $grade grade_grade
4e781c7b 1106 * @return int Completion state e.g. COMPLETION_INCOMPLETE
1107 */
91537a88 1108 function internal_get_grade_state($item, $grade) {
0d5d12bd 1109 if (!$grade) {
4e781c7b 1110 return COMPLETION_INCOMPLETE;
1111 }
1112 // Conditions to show pass/fail:
1113 // a) Grade has pass mark (default is 0.00000 which is boolean true so be careful)
1114 // b) Grade is visible (neither hidden nor hidden-until)
0d5d12bd 1115 if ($item->gradepass && $item->gradepass > 0.000009 && !$item->hidden) {
4e781c7b 1116 // Use final grade if set otherwise raw grade
0d5d12bd 1117 $score = !is_null($grade->finalgrade) ? $grade->finalgrade : $grade->rawgrade;
1118
4e781c7b 1119 // We are displaying and tracking pass/fail
0d5d12bd 1120 if ($score >= $item->gradepass) {
4e781c7b 1121 return COMPLETION_COMPLETE_PASS;
1122 } else {
1123 return COMPLETION_COMPLETE_FAIL;
1124 }
1125 } else {
1126 // Not displaying pass/fail, but we know grade exists b/c we got here
1127 return COMPLETION_COMPLETE;
1128 }
1129 }
0d5d12bd 1130
4e781c7b 1131 /**
4e781c7b 1132 * This is to be used only for system errors (things that shouldn't happen)
1133 * and not user-level errors.
1134 *
09639ded 1135 * @global object
4e781c7b 1136 * @param string $error Error string (will not be displayed to user unless
1137 * debugging is enabled)
09639ded 1138 * @return void Throws moodle_exception Exception with the error string as debug info
4e781c7b 1139 */
1140 function internal_systemerror($error) {
1141 global $CFG;
82bd6a5e 1142 throw new moodle_exception('err_system','completion',
1143 $CFG->wwwroot.'/course/view.php?id='.$this->course->id,null,$error);
1144 }
d7d87535 1145
117bd748
PS
1146 /**
1147 * For testing only. Wipes information cached in user session.
09639ded 1148 *
1149 * @global object
1150 */
82bd6a5e 1151 static function wipe_session_cache() {
1152 global $SESSION;
1153 unset($SESSION->completioncache);
1154 unset($SESSION->completioncacheuserid);
4e781c7b 1155 }
1156}