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