backup MDL-22251 fixed issue with delete_old_backup_dirs passing a full path rather...
[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 *
09639ded 24 * @package moodlecore
3564771d 25 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
09639ded 26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 */
4e781c7b 28
29/** The completion system is enabled in this site/course */
0d5d12bd 30define('COMPLETION_ENABLED', 1);
4e781c7b 31/** The completion system is not enabled in this site/course */
0d5d12bd 32define('COMPLETION_DISABLED', 0);
4e781c7b 33
34// Completion tracking options per-activity (course_modules/completion)
35
36/** Completion tracking is disabled for this activity */
0d5d12bd 37define('COMPLETION_TRACKING_NONE', 0);
4e781c7b 38/** Manual completion tracking (user ticks box) is enabled for this activity */
0d5d12bd 39define('COMPLETION_TRACKING_MANUAL', 1);
4e781c7b 40/** Automatic completion tracking (system ticks box) is enabled for this activity */
0d5d12bd 41define('COMPLETION_TRACKING_AUTOMATIC', 2);
4e781c7b 42
43// Completion state values (course_modules_completion/completionstate)
44
45/** The user has not completed this activity. */
0d5d12bd 46define('COMPLETION_INCOMPLETE', 0);
4e781c7b 47/** The user has completed this activity. It is not specified whether they have
48 * passed or failed it. */
0d5d12bd 49define('COMPLETION_COMPLETE', 1);
4e781c7b 50/** The user has completed this activity with a grade above the pass mark. */
0d5d12bd 51define('COMPLETION_COMPLETE_PASS', 2);
4e781c7b 52/** The user has completed this activity but their grade is less than the pass mark */
0d5d12bd 53define('COMPLETION_COMPLETE_FAIL', 3);
4e781c7b 54
0d5d12bd 55// Completion effect changes (used only in update_state)
4e781c7b 56
57/** The effect of this change to completion status is unknown. */
0d5d12bd 58define('COMPLETION_UNKNOWN', -1);
59/** The user's grade has changed, so their new state might be
4e781c7b 60 * COMPLETION_COMPLETE_PASS or COMPLETION_COMPLETE_FAIL. */
61// TODO Is this useful?
0d5d12bd 62define('COMPLETION_GRADECHANGE', -2);
4e781c7b 63
64// Whether view is required to create an activity (course_modules/completionview)
65
66/** User must view this activity */
0d5d12bd 67define('COMPLETION_VIEW_REQUIRED', 1);
4e781c7b 68/** User does not need to view this activity */
0d5d12bd 69define('COMPLETION_VIEW_NOT_REQUIRED', 0);
4e781c7b 70
71// Completion viewed state (course_modules_completion/viewed)
72
73/** User has viewed this activity */
0d5d12bd 74define('COMPLETION_VIEWED', 1);
4e781c7b 75/** User has not viewed this activity */
0d5d12bd 76define('COMPLETION_NOT_VIEWED', 0);
4e781c7b 77
78// Completion cacheing
79
80/** Cache expiry time in seconds (10 minutes) */
0d5d12bd 81define('COMPLETION_CACHE_EXPIRY', 10*60);
4e781c7b 82
83// Combining completion condition. This is also the value you should return
84// if you don't have any applicable conditions.
0d5d12bd 85/** Completion details should be ORed together and you should return false if
4e781c7b 86 none apply */
0d5d12bd 87define('COMPLETION_OR', false);
88/** Completion details should be ANDed together and you should return true if
4e781c7b 89 none apply */
0d5d12bd 90define('COMPLETION_AND', true);
4e781c7b 91
92/**
93 * Class represents completion information for a course.
09639ded 94 *
95 * Does not contain any data, so you can safely construct it multiple times
96 * without causing any problems.
97 *
98 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
99 * @package moodlecore
4e781c7b 100 */
101class completion_info {
09639ded 102 /** @var object Passed during construction */
4e781c7b 103 private $course;
0d5d12bd 104
4e781c7b 105 /**
106 * Constructs with course details.
107 *
108 * @param object $course Moodle course object. Must have at least ->id, ->enablecompletion
4e781c7b 109 */
49f6e5f4 110 public function __construct($course) {
0d5d12bd 111 $this->course = $course;
4e781c7b 112 }
113
114 /**
09639ded 115 * Determines whether completion is enabled across entire site.
117bd748
PS
116 *
117 * Static function.
4e781c7b 118 *
09639ded 119 * @global object
0d5d12bd 120 * @return int COMPLETION_ENABLED (true) if completion is enabled for the site,
4e781c7b 121 * COMPLETION_DISABLED (false) if it's complete
122 */
123 public static function is_enabled_for_site() {
124 global $CFG;
1caea91e 125 return !empty($CFG->enablecompletion);
4e781c7b 126 }
0d5d12bd 127
4e781c7b 128 /**
129 * Checks whether completion is enabled in a particular course and possibly
130 * activity.
131 *
09639ded 132 * @global object
133 * @uses COMPLETION_DISABLED
134 * @uses COMPLETION_ENABLED
4e781c7b 135 * @param object $cm Course-module object. If not specified, returns the course
136 * completion enable state.
09639ded 137 * @return mixed COMPLETION_ENABLED or COMPLETION_DISABLED (==0) in the case of
4e781c7b 138 * site and course; COMPLETION_TRACKING_MANUAL, _AUTOMATIC or _NONE (==0)
139 * for a course-module.
140 */
141 public function is_enabled($cm=null) {
4e781c7b 142 global $CFG;
d7d87535 143
144 // First check global completion
0d5d12bd 145 if ($CFG->enablecompletion == COMPLETION_DISABLED) {
4e781c7b 146 return COMPLETION_DISABLED;
147 }
0d5d12bd 148
4e781c7b 149 // Check course completion
0d5d12bd 150 if ($this->course->enablecompletion == COMPLETION_DISABLED) {
4e781c7b 151 return COMPLETION_DISABLED;
152 }
0d5d12bd 153
4e781c7b 154 // If there was no $cm and we got this far, then it's enabled
0d5d12bd 155 if (!$cm) {
4e781c7b 156 return COMPLETION_ENABLED;
157 }
0d5d12bd 158
4e781c7b 159 // Return course-module completion value
160 return $cm->completion;
161 }
0d5d12bd 162
e3568fde 163 /**
164 * Print the Your progress help icon if the completion tracking is enabled.
165 * @global object
166 * @return void
167 */
168 public function print_help_icon() {
aa9a6867 169 global $PAGE, $OUTPUT;
e3568fde 170 if ($this->is_enabled() && !$PAGE->user_is_editing() && isloggedin() && !isguestuser()) {
905b1de6 171 echo '<span id = "completionprogressid" class="completionprogress">'.get_string('yourprogress','completion').' ';
596509e4 172 echo $OUTPUT->old_help_icon('completionicons',get_string('completionicons','completion'),'completion');
e3568fde 173 echo '</span>';
174 }
175 }
176 // OU specific end
4e781c7b 177 /**
178 * Updates (if necessary) the completion state of activity $cm for the given
179 * user.
09639ded 180 *
4e781c7b 181 * For manual completion, this function is called when completion is toggled
182 * with $possibleresult set to the target state.
09639ded 183 *
4e781c7b 184 * For automatic completion, this function should be called every time a module
185 * does something which might influence a user's completion state. For example,
186 * if a forum provides options for marking itself 'completed' once a user makes
187 * N posts, this function should be called every time a user makes a new post.
188 * [After the post has been saved to the database]. When calling, you do not
189 * need to pass in the new completion state. Instead this function carries out
190 * completion calculation by checking grades and viewed state itself, and
191 * calling the involved module via modulename_get_completion_state() to check
192 * module-specific conditions.
193 *
09639ded 194 * @global object
195 * @global object
196 * @uses COMPLETION_COMPLETE
197 * @uses COMPLETION_INCOMPLETE
198 * @uses COMPLETION_COMPLETE_PASS
199 * @uses COMPLETION_COMPLETE_FAIL
200 * @uses COMPLETION_TRACKING_MANUAL
4e781c7b 201 * @param object $cm Course-module
202 * @param int $possibleresult Expected completion result. If the event that
203 * has just occurred (e.g. add post) can only result in making the activity
204 * complete when it wasn't before, use COMPLETION_COMPLETE. If the event that
205 * has just occurred (e.g. delete post) can only result in making the activity
206 * not complete when it was previously complete, use COMPLETION_INCOMPLETE.
207 * Otherwise use COMPLETION_UNKNOWN. Setting this value to something other than
208 * COMPLETION_UNKNOWN significantly improves performance because it will abandon
209 * processing early if the user's completion state already matches the expected
210 * result. For manual events, COMPLETION_COMPLETE or COMPLETION_INCOMPLETE
211 * must be used; these directly set the specified state.
212 * @param int $userid User ID to be updated. Default 0 = current user
09639ded 213 * @return void
4e781c7b 214 */
0d5d12bd 215 public function update_state($cm, $possibleresult=COMPLETION_UNKNOWN, $userid=0) {
216 global $USER, $SESSION;
d7d87535 217
0d5d12bd 218 // Do nothing if completion is not enabled for that activity
219 if (!$this->is_enabled($cm)) {
4e781c7b 220 return;
221 }
0d5d12bd 222
4e781c7b 223 // Get current value of completion state and do nothing if it's same as
224 // the possible result of this change. If the change is to COMPLETE and the
225 // current value is one of the COMPLETE_xx subtypes, ignore that as well
0d5d12bd 226 $current = $this->get_data($cm, false, $userid);
227 if ($possibleresult == $current->completionstate ||
228 ($possibleresult == COMPLETION_COMPLETE &&
229 ($current->completionstate == COMPLETION_COMPLETE_PASS ||
230 $current->completionstate == COMPLETION_COMPLETE_FAIL))) {
4e781c7b 231 return;
232 }
0d5d12bd 233
234 if ($cm->completion == COMPLETION_TRACKING_MANUAL) {
4e781c7b 235 // For manual tracking we set the result directly
236 switch($possibleresult) {
237 case COMPLETION_COMPLETE:
238 case COMPLETION_INCOMPLETE:
0d5d12bd 239 $newstate = $possibleresult;
4e781c7b 240 break;
241 default:
242 $this->internal_systemerror("Unexpected manual completion state for {$cm->id}: $possibleresult");
243 }
d7d87535 244
4e781c7b 245 } else {
246 // Automatic tracking; get new state
0d5d12bd 247 $newstate = $this->internal_get_state($cm, $userid, $current);
4e781c7b 248 }
0d5d12bd 249
4e781c7b 250 // If changed, update
0d5d12bd 251 if ($newstate != $current->completionstate) {
252 $current->completionstate = $newstate;
253 $current->timemodified = time();
254 $this->internal_set_data($cm, $current);
4e781c7b 255 }
256 }
0d5d12bd 257
4e781c7b 258 /**
259 * Calculates the completion state for an activity and user.
4e781c7b 260 *
09639ded 261 * Internal function. Not private, so we can unit-test it.
262 *
263 * @global object
264 * @global object
265 * @global object
266 * @uses COMPLETION_VIEW_REQUIRED
267 * @uses COMPLETION_NOT_VIEWED
268 * @uses COMPLETION_INCOMPLETE
269 * @uses FEATURE_COMPLETION_HAS_RULES
270 * @uses COMPLETION_COMPLETE
271 * @uses COMPLETION_AND
4e781c7b 272 * @param object $cm Activity
273 * @param int $userid ID of user
274 * @param object $current Previous completion information from database
09639ded 275 * @return mixed
4e781c7b 276 */
0d5d12bd 277 function internal_get_state($cm, $userid, $current) {
7a7dbd77 278 global $USER, $DB, $CFG;
d7d87535 279
280 // Get user ID
0d5d12bd 281 if (!$userid) {
282 $userid = $USER->id;
4e781c7b 283 }
0d5d12bd 284
4e781c7b 285 // Check viewed
0d5d12bd 286 if ($cm->completionview == COMPLETION_VIEW_REQUIRED &&
287 $current->viewed == COMPLETION_NOT_VIEWED) {
288
4e781c7b 289 return COMPLETION_INCOMPLETE;
290 }
0d5d12bd 291
4e781c7b 292 // Modname hopefully is provided in $cm but just in case it isn't, let's grab it
0d5d12bd 293 if (!isset($cm->modname)) {
294 $cm->modname = $DB->get_field('modules', 'name', array('id'=>$cm->module));
4e781c7b 295 }
0d5d12bd 296
297 $newstate = COMPLETION_COMPLETE;
298
4e781c7b 299 // Check grade
0d5d12bd 300 if (!is_null($cm->completiongradeitemnumber)) {
7a7dbd77 301 require_once($CFG->libdir.'/gradelib.php');
0d5d12bd 302 $item = grade_item::fetch(array('courseid'=>$cm->course, 'itemtype'=>'mod',
303 'itemmodule'=>$cm->modname, 'iteminstance'=>$cm->instance,
4e781c7b 304 'itemnumber'=>$cm->completiongradeitemnumber));
0d5d12bd 305 if ($item) {
4e781c7b 306 // Fetch 'grades' (will be one or none)
0d5d12bd 307 $grades = grade_grade::fetch_users_grades($item, array($userid), false);
308 if (empty($grades)) {
4e781c7b 309 // No grade for user
310 return COMPLETION_INCOMPLETE;
311 }
0d5d12bd 312 if (count($grades) > 1) {
4e781c7b 313 $this->internal_systemerror("Unexpected result: multiple grades for
314 item '{$item->id}', user '{$userid}'");
315 }
0d5d12bd 316 $newstate = $this->internal_get_grade_state($item, reset($grades));
317 if ($newstate == COMPLETION_INCOMPLETE) {
4e781c7b 318 return COMPLETION_INCOMPLETE;
319 }
d7d87535 320
4e781c7b 321 } else {
322 $this->internal_systemerror("Cannot find grade item for '{$cm->modname}'
323 cm '{$cm->id}' matching number '{$cm->completiongradeitemnumber}'");
324 }
325 }
0d5d12bd 326
327 if (plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_HAS_RULES)) {
328 $function = $cm->modname.'_get_completion_state';
329 if (!function_exists($function)) {
4e781c7b 330 $this->internal_systemerror("Module {$cm->modname} claims to support
331 FEATURE_COMPLETION_HAS_RULES but does not have required
332 {$cm->modname}_get_completion_state function");
333 }
0d5d12bd 334 if (!$function($this->course, $cm, $userid, COMPLETION_AND)) {
4e781c7b 335 return COMPLETION_INCOMPLETE;
336 }
337 }
0d5d12bd 338
4e781c7b 339 return $newstate;
0d5d12bd 340
4e781c7b 341 }
0d5d12bd 342
343
4e781c7b 344 /**
345 * Marks a module as viewed.
09639ded 346 *
4e781c7b 347 * Should be called whenever a module is 'viewed' (it is up to the module how to
348 * determine that). Has no effect if viewing is not set as a completion condition.
349 *
09639ded 350 * @uses COMPLETION_VIEW_NOT_REQUIRED
351 * @uses COMPLETION_VIEWED
352 * @uses COMPLETION_COMPLETE
4e781c7b 353 * @param object $cm Activity
354 * @param int $userid User ID or 0 (default) for current user
09639ded 355 * @return void
4e781c7b 356 */
0d5d12bd 357 public function set_module_viewed($cm, $userid=0) {
4e781c7b 358 // Don't do anything if view condition is not turned on
0d5d12bd 359 if ($cm->completionview == COMPLETION_VIEW_NOT_REQUIRED || !$this->is_enabled($cm)) {
4e781c7b 360 return;
361 }
362 // Get current completion state
0d5d12bd 363 $data = $this->get_data($cm, $userid);
4e781c7b 364 // If we already viewed it, don't do anything
0d5d12bd 365 if ($data->viewed == COMPLETION_VIEWED) {
4e781c7b 366 return;
367 }
368 // OK, change state, save it, and update completion
0d5d12bd 369 $data->viewed = COMPLETION_VIEWED;
370 $this->internal_set_data($cm, $data);
371 $this->update_state($cm, COMPLETION_COMPLETE, $userid);
4e781c7b 372 }
0d5d12bd 373
4e781c7b 374 /**
375 * Determines how much completion data exists for an activity. This is used when
376 * deciding whether completion information should be 'locked' in the module
377 * editing form.
378 *
09639ded 379 * @global object
380 * @global object
4e781c7b 381 * @param object $cm Activity
382 * @return int The number of users who have completion data stored for this
0d5d12bd 383 * activity, 0 if none
4e781c7b 384 */
385 public function count_user_data($cm) {
0d5d12bd 386 global $CFG, $DB;
387
4e781c7b 388 return $DB->get_field_sql("
389 SELECT
390 COUNT(1)
391 FROM
49f6e5f4 392 {course_modules_completion}
4e781c7b 393 WHERE
0d5d12bd 394 coursemoduleid=? AND completionstate<>0", array($cm->id));
4e781c7b 395 }
0d5d12bd 396
4e781c7b 397 /**
0d5d12bd 398 * Deletes completion state related to an activity for all users.
117bd748 399 *
4e781c7b 400 * Intended for use only when the activity itself is deleted.
401 *
09639ded 402 * @global object
403 * @global object
4e781c7b 404 * @param object $cm Activity
405 */
0d5d12bd 406 public function delete_all_state($cm) {
407 global $SESSION, $DB;
408
4e781c7b 409 // Delete from database
0d5d12bd 410 $DB->delete_records('course_modules_completion', array('coursemoduleid'=>$cm->id));
411
4e781c7b 412 // Erase cache data for current user if applicable
0d5d12bd 413 if (isset($SESSION->completioncache) &&
414 array_key_exists($cm->course, $SESSION->completioncache) &&
415 array_key_exists($cm->id, $SESSION->completioncache[$cm->course])) {
416
4e781c7b 417 unset($SESSION->completioncache[$cm->course][$cm->id]);
418 }
419 }
0d5d12bd 420
4e781c7b 421 /**
422 * Recalculates completion state related to an activity for all users.
117bd748 423 *
4e781c7b 424 * Intended for use if completion conditions change. (This should be avoided
425 * as it may cause some things to become incomplete when they were previously
426 * complete, with the effect - for example - of hiding a later activity that
427 * was previously available.)
117bd748 428 *
0d5d12bd 429 * Resetting state of manual tickbox has same result as deleting state for
81f64ed3 430 * it.
09639ded 431 *
432 * @global object
433 * @uses COMPLETION_TRACKING_MANUAL
434 * @uses COMPLETION_UNKNOWN
4e781c7b 435 * @param object $cm Activity
436 */
437 public function reset_all_state($cm) {
d7d87535 438 global $DB;
439
0d5d12bd 440 if ($cm->completion == COMPLETION_TRACKING_MANUAL) {
81f64ed3 441 $this->delete_all_state($cm);
442 return;
443 }
4e781c7b 444 // Get current list of users with completion state
0d5d12bd 445 $rs = $DB->get_recordset('course_modules_completion', array('coursemoduleid'=>$cm->id), '', 'userid');
446 $keepusers = array();
447 foreach ($rs as $rec) {
448 $keepusers[] = $rec->userid;
4e781c7b 449 }
450 $rs->close();
0d5d12bd 451
4e781c7b 452 // Delete all existing state [also clears session cache for current user]
453 $this->delete_all_state($cm);
0d5d12bd 454
455 // Merge this with list of planned users (according to roles)
456 $trackedusers = $this->internal_get_tracked_users(false);
457 foreach ($trackedusers as $trackeduser) {
458 $keepusers[] = $trackeduser->id;
459 }
460 $keepusers = array_unique($keepusers);
461
4e781c7b 462 // Recalculate state for each kept user
0d5d12bd 463 foreach ($keepusers as $keepuser) {
464 $this->update_state($cm, COMPLETION_UNKNOWN, $keepuser);
4e781c7b 465 }
466 }
0d5d12bd 467
4e781c7b 468 /**
469 * Obtains completion data for a particular activity and user (from the
470 * session cache if available, or by SQL query)
471 *
09639ded 472 * @global object
473 * @global object
474 * @global object
475 * @global object
476 * @uses COMPLETION_CACHE_EXPIRY
82bd6a5e 477 * @param object $cm Activity; only required field is ->id
4e781c7b 478 * @param bool $wholecourse If true (default false) then, when necessary to
479 * fill the cache, retrieves information from the entire course not just for
480 * this one activity
481 * @param int $userid User ID or 0 (default) for current user
117bd748
PS
482 * @param array $modinfo Supply the value here - this is used for unit
483 * testing and so that it can be called recursively from within
82bd6a5e 484 * get_fast_modinfo. (Needs only list of all CMs with IDs.)
485 * Otherwise the method calls get_fast_modinfo itself.
4e781c7b 486 * @return object Completion data (record from course_modules_completion)
4e781c7b 487 */
0d5d12bd 488 public function get_data($cm, $wholecourse=false, $userid=0, $modinfo=null) {
0d5d12bd 489 global $USER, $CFG, $SESSION, $DB;
d7d87535 490
491 // Get user ID
0d5d12bd 492 if (!$userid) {
493 $userid = $USER->id;
4e781c7b 494 }
0d5d12bd 495
4e781c7b 496 // Is this the current user?
0d5d12bd 497 $currentuser = $userid==$USER->id;
498
499 if ($currentuser) {
500 // Make sure cache is present and is for current user (loginas
49f6e5f4 501 // changes this)
0d5d12bd 502 if (!isset($SESSION->completioncache) || $SESSION->completioncacheuserid!=$USER->id) {
503 $SESSION->completioncache = array();
504 $SESSION->completioncacheuserid = $USER->id;
4e781c7b 505 }
506 // Expire any old data from cache
0d5d12bd 507 foreach ($SESSION->completioncache as $courseid=>$activities) {
508 if (empty($activities['updated']) || $activities['updated'] < time()-COMPLETION_CACHE_EXPIRY) {
4e781c7b 509 unset($SESSION->completioncache[$courseid]);
510 }
511 }
512 // See if requested data is present, if so use cache to get it
0d5d12bd 513 if (isset($SESSION->completioncache) &&
514 array_key_exists($this->course->id, $SESSION->completioncache) &&
515 array_key_exists($cm->id, $SESSION->completioncache[$this->course->id])) {
516 return $SESSION->completioncache[$this->course->id][$cm->id];
4e781c7b 517 }
518 }
0d5d12bd 519
4e781c7b 520 // Not there, get via SQL
0d5d12bd 521 if ($currentuser && $wholecourse) {
4e781c7b 522 // Get whole course data for cache
0d5d12bd 523 $alldatabycmc = $DB->get_records_sql("
4e781c7b 524 SELECT
525 cmc.*
526 FROM
49f6e5f4 527 {course_modules} cm
528 INNER JOIN {course_modules_completion} cmc ON cmc.coursemoduleid=cm.id
0d5d12bd 529 WHERE
530 cm.course=? AND cmc.userid=?", array($this->course->id, $userid));
531
4e781c7b 532 // Reindex by cm id
0d5d12bd 533 $alldata = array();
534 if ($alldatabycmc) {
535 foreach ($alldatabycmc as $data) {
536 $alldata[$data->coursemoduleid] = $data;
4e781c7b 537 }
538 }
0d5d12bd 539
4e781c7b 540 // Get the module info and build up condition info for each one
0d5d12bd 541 if (empty($modinfo)) {
542 $modinfo = get_fast_modinfo($this->course, $userid);
4e781c7b 543 }
0d5d12bd 544 foreach ($modinfo->cms as $othercm) {
545 if (array_key_exists($othercm->id, $alldata)) {
546 $data = $alldata[$othercm->id];
4e781c7b 547 } else {
548 // Row not present counts as 'not complete'
0d5d12bd 549 $data = new StdClass;
550 $data->id = 0;
551 $data->coursemoduleid = $othercm->id;
552 $data->userid = $userid;
553 $data->completionstate = 0;
554 $data->viewed = 0;
555 $data->timemodified = 0;
4e781c7b 556 }
0d5d12bd 557 $SESSION->completioncache[$this->course->id][$othercm->id] = $data;
4e781c7b 558 }
0d5d12bd 559 $SESSION->completioncache[$this->course->id]['updated'] = time();
560
561 if (!isset($SESSION->completioncache[$this->course->id][$cm->id])) {
4e781c7b 562 $this->internal_systemerror("Unexpected error: course-module {$cm->id} could not be found on course {$this->course->id}");
563 }
564 return $SESSION->completioncache[$this->course->id][$cm->id];
d7d87535 565
4e781c7b 566 } else {
567 // Get single record
0d5d12bd 568 $data = $DB->get_record('course_modules_completion', array('coursemoduleid'=>$cm->id, 'userid'=>$userid));
569 if ($data == false) {
4e781c7b 570 // Row not present counts as 'not complete'
0d5d12bd 571 $data = new StdClass;
572 $data->id = 0;
573 $data->coursemoduleid = $cm->id;
574 $data->userid = $userid;
575 $data->completionstate = 0;
576 $data->viewed = 0;
577 $data->timemodified = 0;
4e781c7b 578 }
0d5d12bd 579
4e781c7b 580 // Put in cache
0d5d12bd 581 if ($currentuser) {
582 $SESSION->completioncache[$this->course->id][$cm->id] = $data;
4e781c7b 583 // For single updates, only set date if it was empty before
0d5d12bd 584 if (empty($SESSION->completioncache[$this->course->id]['updated'])) {
585 $SESSION->completioncache[$this->course->id]['updated'] = time();
4e781c7b 586 }
587 }
588 }
0d5d12bd 589
4e781c7b 590 return $data;
591 }
0d5d12bd 592
4e781c7b 593 /**
0d5d12bd 594 * Updates completion data for a particular coursemodule and user (user is
4e781c7b 595 * determined from $data).
117bd748 596 *
4e781c7b 597 * (Internal function. Not private, so we can unit-test it.)
0d5d12bd 598 *
09639ded 599 * @global object
600 * @global object
601 * @global object
4e781c7b 602 * @param object $cm Activity
603 * @param object $data Data about completion for that user
604 */
0d5d12bd 605 function internal_set_data($cm, $data) {
606 global $USER, $SESSION, $DB;
d7d87535 607
0d5d12bd 608 if ($data->id) {
4e781c7b 609 // Has real (nonzero) id meaning that a database row exists
0d5d12bd 610 $DB->update_record('course_modules_completion', $data);
611 } else {
4e781c7b 612 // Didn't exist before, needs creating
0d5d12bd 613 $data->id = $DB->insert_record('course_modules_completion', $data);
4e781c7b 614 }
d7d87535 615
0d5d12bd 616 if ($data->userid == $USER->id) {
617 $SESSION->completioncache[$cm->course][$cm->id] = $data;
4e781c7b 618 }
619 }
0d5d12bd 620
4e781c7b 621 /**
0d5d12bd 622 * Obtains a list of activities for which completion is enabled on the
4e781c7b 623 * course. The list is ordered by the section order of those activities.
09639ded 624 *
625 * @global object
626 * @uses COMPLETION_TRACKING_NONE
0d5d12bd 627 * @param array $modinfo For unit testing only, supply the value
4e781c7b 628 * here. Otherwise the method calls get_fast_modinfo
629 * @return array Array from $cmid => $cm of all activities with completion enabled,
630 * empty array if none
631 */
632 public function get_activities($modinfo=null) {
633 global $DB;
0d5d12bd 634
4e781c7b 635 // Obtain those activities which have completion turned on
0d5d12bd 636 $withcompletion = $DB->get_records_select('course_modules', 'course='.$this->course->id.
4e781c7b 637 ' AND completion<>'.COMPLETION_TRACKING_NONE);
0d5d12bd 638 if (count($withcompletion) == 0) {
4e781c7b 639 return array();
640 }
0d5d12bd 641
4e781c7b 642 // Use modinfo to get section order and also add in names
0d5d12bd 643 if (empty($modinfo)) {
644 $modinfo = get_fast_modinfo($this->course);
645 }
646 $result = array();
647 foreach ($modinfo->sections as $sectioncms) {
648 foreach ($sectioncms as $cmid) {
649 if (array_key_exists($cmid, $withcompletion)) {
650 $result[$cmid] = $withcompletion[$cmid];
651 $result[$cmid]->modname = $modinfo->cms[$cmid]->modname;
652 $result[$cmid]->name = $modinfo->cms[$cmid]->name;
4e781c7b 653 }
654 }
655 }
0d5d12bd 656
4e781c7b 657 return $result;
658 }
0d5d12bd 659
4e781c7b 660 /**
0d5d12bd 661 * Gets list of users in a course whose progress is tracked for display on the
4e781c7b 662 * progress report.
09639ded 663 *
664 * @global object
665 * @global object
666 * @uses CONTEXT_COURSE
4e781c7b 667 * @param bool $sortfirstname True to sort with firstname
668 * @param int $groupid Optionally restrict to groupid
669 * @return array Array of user objects containing id, firstname, lastname (empty if none)
670 */
0d5d12bd 671 function internal_get_tracked_users($sortfirstname, $groupid=0) {
672 global $CFG, $DB;
d7d87535 673
0d5d12bd 674 if (!empty($CFG->progresstrackedroles)) {
675 $roles = explode(', ', $CFG->progresstrackedroles);
4e781c7b 676 } else {
677 // This causes it to default to everyone (if there is no student role)
0d5d12bd 678 $roles = array();
4e781c7b 679 }
0d5d12bd 680 $users = get_role_users($roles, get_context_instance(CONTEXT_COURSE, $this->course->id), true,
681 'u.id, u.firstname, u.lastname, u.idnumber',
682 $sortfirstname ? 'u.firstname ASC' : 'u.lastname ASC', true, $groupid);
683 $users = $users ? $users : array(); // In case it returns false
4e781c7b 684 return $users;
685 }
0d5d12bd 686
4e781c7b 687 /**
688 * Obtains progress information across a course for all users on that course, or
689 * for all users in a specific group. Intended for use when displaying progress.
117bd748 690 *
4e781c7b 691 * This includes only users who, in course context, have one of the roles for
692 * which progress is tracked (the progresstrackedroles admin option).
117bd748 693 *
4e781c7b 694 * Users are included (in the first array) even if they do not have
695 * completion progress for any course-module.
696 *
09639ded 697 * @global object
698 * @global object
4e781c7b 699 * @param bool $sortfirstname If true, sort by first name, otherwise sort by
700 * last name
701 * @param int $groupid Group ID or 0 (default)/false for all groups
35da0e87 702 * @param int $pagesize Number of users to actually return (0 = unlimited)
703 * @param int $start User to start at if paging (0 = first set)
704 * @return Object with ->total and ->start (same as $start) and ->users;
705 * an array of user objects (like mdl_user id, firstname, lastname)
4e781c7b 706 * containing an additional ->progress array of coursemoduleid => completionstate
707 */
35da0e87 708 public function get_progress_all($sortfirstname=false, $groupid=0,
9b0e2d66 709 $pagesize=0,$start=0) {
0d5d12bd 710 global $CFG, $DB;
35da0e87 711 $resultobject=new StdClass;
0d5d12bd 712
4e781c7b 713 // Get list of applicable users
0d5d12bd 714 $users = $this->internal_get_tracked_users($sortfirstname, $groupid);
35da0e87 715 $resultobject->start=$start;
716 $resultobject->total=count($users);
002f56ef 717 $users=array_slice($users,$start,$pagesize==0 ? count($users)-$start : $pagesize);
0d5d12bd 718
719 // Get progress information for these users in groups of 1, 000 (if needed)
4e781c7b 720 // to avoid making the SQL IN too long
35da0e87 721 $resultobject->users=array();
0d5d12bd 722 $userids = array();
723 foreach ($users as $user) {
724 $userids[] = $user->id;
35da0e87 725 $resultobject->users[$user->id]=$user;
82bd6a5e 726 $resultobject->users[$user->id]->progress=array();
0d5d12bd 727 }
728
729 for($i=0; $i<count($userids); $i+=1000) {
730 $blocksize = count($userids)-$i < 1000 ? count($userids)-$i : 1000;
731
732 list($insql, $params) = $DB->get_in_or_equal(array_slice($userids, $i, $blocksize));
733 array_splice($params, 0, 0, array($this->course->id));
734 $rs = $DB->get_recordset_sql("
4e781c7b 735SELECT
736 cmc.*
737FROM
49f6e5f4 738 {course_modules} cm
739 INNER JOIN {course_modules_completion} cmc ON cm.id=cmc.coursemoduleid
4e781c7b 740WHERE
741 cm.course=? AND cmc.userid $insql
0d5d12bd 742 ", $params);
0d5d12bd 743 foreach ($rs as $progress) {
35da0e87 744 $resultobject->users[$progress->userid]->progress[$progress->coursemoduleid]=$progress;
4e781c7b 745 }
746 $rs->close();
747 }
0d5d12bd 748
35da0e87 749 return $resultobject;
4e781c7b 750 }
0d5d12bd 751
09639ded 752 /**
753 * @todo Document this function
754 *
755 * @uses COMPLETION_TRACKING_MANUAL
756 * @uses COMPLETION_INCOMPLETE
757 * @param object $cm
758 * @param object $item
759 * @param object $grade
760 * @param bool $deleted
761 * @return void
762 */
91537a88 763 public function inform_grade_changed($cm, $item, $grade, $deleted) {
ca6b2d68 764 // Bail out now if completion is not enabled for course-module, it is enabled
765 // but is set to manual, grade is not used to compute completion, or this
766 // is a different numbered grade
0d5d12bd 767 if (!$this->is_enabled($cm) ||
ca6b2d68 768 $cm->completion == COMPLETION_TRACKING_MANUAL ||
4e781c7b 769 is_null($cm->completiongradeitemnumber) ||
0d5d12bd 770 $item->itemnumber != $cm->completiongradeitemnumber) {
d7d87535 771
4e781c7b 772 return;
773 }
0d5d12bd 774
4e781c7b 775 // What is the expected result based on this grade?
0d5d12bd 776 if ($deleted) {
4e781c7b 777 // Grade being deleted, so only change could be to make it incomplete
0d5d12bd 778 $possibleresult = COMPLETION_INCOMPLETE;
4e781c7b 779 } else {
0d5d12bd 780 $possibleresult = $this->internal_get_grade_state($item, $grade);
4e781c7b 781 }
0d5d12bd 782
4e781c7b 783 // OK, let's update state based on this
0d5d12bd 784 $this->update_state($cm, $possibleresult, $grade->userid);
4e781c7b 785 }
0d5d12bd 786
4e781c7b 787 /**
788 * Calculates the completion state that would result from a graded item
789 * (where grade-based completion is turned on) based on the actual grade
790 * and settings.
117bd748 791 *
09639ded 792 * Internal function. Not private, so we can unit-test it.
4e781c7b 793 *
09639ded 794 * @uses COMPLETION_INCOMPLETE
795 * @uses COMPLETION_COMPLETE_PASS
796 * @uses COMPLETION_COMPLETE_FAIL
797 * @uses COMPLETION_COMPLETE
798 * @param object $item grade_item
799 * @param object $grade grade_grade
4e781c7b 800 * @return int Completion state e.g. COMPLETION_INCOMPLETE
801 */
91537a88 802 function internal_get_grade_state($item, $grade) {
0d5d12bd 803 if (!$grade) {
4e781c7b 804 return COMPLETION_INCOMPLETE;
805 }
806 // Conditions to show pass/fail:
807 // a) Grade has pass mark (default is 0.00000 which is boolean true so be careful)
808 // b) Grade is visible (neither hidden nor hidden-until)
0d5d12bd 809 if ($item->gradepass && $item->gradepass > 0.000009 && !$item->hidden) {
4e781c7b 810 // Use final grade if set otherwise raw grade
0d5d12bd 811 $score = !is_null($grade->finalgrade) ? $grade->finalgrade : $grade->rawgrade;
812
4e781c7b 813 // We are displaying and tracking pass/fail
0d5d12bd 814 if ($score >= $item->gradepass) {
4e781c7b 815 return COMPLETION_COMPLETE_PASS;
816 } else {
817 return COMPLETION_COMPLETE_FAIL;
818 }
819 } else {
820 // Not displaying pass/fail, but we know grade exists b/c we got here
821 return COMPLETION_COMPLETE;
822 }
823 }
0d5d12bd 824
4e781c7b 825 /**
4e781c7b 826 * This is to be used only for system errors (things that shouldn't happen)
827 * and not user-level errors.
828 *
09639ded 829 * @global object
4e781c7b 830 * @param string $error Error string (will not be displayed to user unless
831 * debugging is enabled)
09639ded 832 * @return void Throws moodle_exception Exception with the error string as debug info
4e781c7b 833 */
834 function internal_systemerror($error) {
835 global $CFG;
82bd6a5e 836 throw new moodle_exception('err_system','completion',
837 $CFG->wwwroot.'/course/view.php?id='.$this->course->id,null,$error);
838 }
d7d87535 839
117bd748
PS
840 /**
841 * For testing only. Wipes information cached in user session.
09639ded 842 *
843 * @global object
844 */
82bd6a5e 845 static function wipe_session_cache() {
846 global $SESSION;
847 unset($SESSION->completioncache);
848 unset($SESSION->completioncacheuserid);
4e781c7b 849 }
850}