completionlib.php 66.6 KB
Newer Older
sam_marshall's avatar
sam_marshall committed
1
<?php
2
3
// This file is part of Moodle - http://moodle.org/
//
4
5
6
7
8
9
10
11
12
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
13
//
14
15
16
17
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
18
19
 * Contains classes, functions and constants used during the tracking
 * of activity completion for users.
20
21
 *
 * Completion top-level options (admin setting enablecompletion)
22
 *
23
24
25
26
 * @package core_completion
 * @category completion
 * @copyright 1999 onwards Martin Dougiamas   {@link http://moodle.com}
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27
 */
sam_marshall's avatar
sam_marshall committed
28

29
30
use core_completion\activity_custom_completion;

31
32
defined('MOODLE_INTERNAL') || die();

33
34
35
/**
 * Include the required completion libraries
 */
36
require_once $CFG->dirroot.'/completion/completion_aggregation.php';
37
require_once $CFG->dirroot.'/completion/criteria/completion_criteria.php';
38
39
require_once $CFG->dirroot.'/completion/completion_completion.php';
require_once $CFG->dirroot.'/completion/completion_criteria_completion.php';
40
41


42
43
44
/**
 * The completion system is enabled in this site/course
 */
skodak's avatar
skodak committed
45
define('COMPLETION_ENABLED', 1);
46
47
48
/**
 * The completion system is not enabled in this site/course
 */
skodak's avatar
skodak committed
49
define('COMPLETION_DISABLED', 0);
sam_marshall's avatar
sam_marshall committed
50

51
52
53
54
/**
 * Completion tracking is disabled for this activity
 * This is a completion tracking option per-activity  (course_modules/completion)
 */
skodak's avatar
skodak committed
55
define('COMPLETION_TRACKING_NONE', 0);
56
57
58
59
60

/**
 * Manual completion tracking (user ticks box) is enabled for this activity
 * This is a completion tracking option per-activity  (course_modules/completion)
 */
skodak's avatar
skodak committed
61
define('COMPLETION_TRACKING_MANUAL', 1);
62
63
64
65
/**
 * Automatic completion tracking (system ticks box) is enabled for this activity
 * This is a completion tracking option per-activity  (course_modules/completion)
 */
skodak's avatar
skodak committed
66
define('COMPLETION_TRACKING_AUTOMATIC', 2);
sam_marshall's avatar
sam_marshall committed
67

68
69
70
71
/**
 * The user has not completed this activity.
 * This is a completion state value (course_modules_completion/completionstate)
 */
skodak's avatar
skodak committed
72
define('COMPLETION_INCOMPLETE', 0);
73
74
75
76
77
/**
 * The user has completed this activity. It is not specified whether they have
 * passed or failed it.
 * This is a completion state value (course_modules_completion/completionstate)
 */
skodak's avatar
skodak committed
78
define('COMPLETION_COMPLETE', 1);
79
80
81
82
/**
 * The user has completed this activity with a grade above the pass mark.
 * This is a completion state value (course_modules_completion/completionstate)
 */
skodak's avatar
skodak committed
83
define('COMPLETION_COMPLETE_PASS', 2);
84
85
86
87
/**
 * The user has completed this activity but their grade is less than the pass mark
 * This is a completion state value (course_modules_completion/completionstate)
 */
skodak's avatar
skodak committed
88
define('COMPLETION_COMPLETE_FAIL', 3);
sam_marshall's avatar
sam_marshall committed
89

90
91
92
93
/**
 * The effect of this change to completion status is unknown.
 * A completion effect changes (used only in update_state)
 */
skodak's avatar
skodak committed
94
define('COMPLETION_UNKNOWN', -1);
95
96
97
98
99
/**
 * The user's grade has changed, so their new state might be
 * COMPLETION_COMPLETE_PASS or COMPLETION_COMPLETE_FAIL.
 * A completion effect changes (used only in update_state)
 */
skodak's avatar
skodak committed
100
define('COMPLETION_GRADECHANGE', -2);
sam_marshall's avatar
sam_marshall committed
101

102
/**
103
 * User must view this activity.
104
105
 * Whether view is required to create an activity (course_modules/completionview)
 */
skodak's avatar
skodak committed
106
define('COMPLETION_VIEW_REQUIRED', 1);
107
108
109
110
/**
 * User does not need to view this activity
 * Whether view is required to create an activity (course_modules/completionview)
 */
skodak's avatar
skodak committed
111
define('COMPLETION_VIEW_NOT_REQUIRED', 0);
sam_marshall's avatar
sam_marshall committed
112

113
114
115
116
/**
 * User has viewed this activity.
 * Completion viewed state (course_modules_completion/viewed)
 */
skodak's avatar
skodak committed
117
define('COMPLETION_VIEWED', 1);
118
119
120
121
/**
 * User has not viewed this activity.
 * Completion viewed state (course_modules_completion/viewed)
 */
skodak's avatar
skodak committed
122
define('COMPLETION_NOT_VIEWED', 0);
sam_marshall's avatar
sam_marshall committed
123

124
125
126
127
/**
 * Completion details should be ORed together and you should return false if
 * none apply.
 */
skodak's avatar
skodak committed
128
define('COMPLETION_OR', false);
129
130
131
132
/**
 * Completion details should be ANDed together and you should return true if
 * none apply
 */
skodak's avatar
skodak committed
133
define('COMPLETION_AND', true);
sam_marshall's avatar
sam_marshall committed
134

135
136
137
138
139
140
141
142
143
144
/**
 * When a module implements this, completion state is dependent to the
 * module's _get_completion_state callback and activity_custom_completion class.
 */
define('COMPLETION_CUSTOM_MODULE_FLOW', true);
/**
 * Standard flow indicates ALL conditions need to be met for completion to be marked as done.
 */
define('COMPLETION_STANDARD_FLOW', false);

145
146
147
148
149
150
151
152
/**
 * Course completion criteria aggregation method.
 */
define('COMPLETION_AGGREGATION_ALL', 1);
/**
 * Course completion criteria aggregation method.
 */
define('COMPLETION_AGGREGATION_ANY', 2);
153

154
155
156
157
158
159
160
161
162
/**
 * Completion conditions will be displayed to user.
 */
define('COMPLETION_SHOW_CONDITIONS', 1);

/**
 * Completion conditions will be hidden from user.
 */
define('COMPLETION_HIDE_CONDITIONS', 0);
163

164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
/**
 * Utility function for checking if the logged in user can view
 * another's completion data for a particular course
 *
 * @access  public
 * @param   int         $userid     Completion data's owner
 * @param   mixed       $course     Course object or Course ID (optional)
 * @return  boolean
 */
function completion_can_view_data($userid, $course = null) {
    global $USER;

    if (!isloggedin()) {
        return false;
    }

    if (!is_object($course)) {
        $cid = $course;
182
        $course = new stdClass();
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
        $course->id = $cid;
    }

    // Check if this is the site course
    if ($course->id == SITEID) {
        $course = null;
    }

    // Check if completion is enabled
    if ($course) {
        $cinfo = new completion_info($course);
        if (!$cinfo->is_enabled()) {
            return false;
        }
    } else {
        if (!completion_info::is_enabled_for_site()) {
            return false;
        }
    }

    // Is own user's data?
    if ($USER->id == $userid) {
        return true;
    }

    // Check capabilities
    $personalcontext = context_user::instance($userid);

    if (has_capability('moodle/user:viewuseractivitiesreport', $personalcontext)) {
        return true;
    } elseif (has_capability('report/completion:view', $personalcontext)) {
        return true;
    }

    if ($course->id) {
        $coursecontext = context_course::instance($course->id);
    } else {
        $coursecontext = context_system::instance();
    }

    if (has_capability('report/completion:view', $coursecontext)) {
        return true;
    }

    return false;
}


sam_marshall's avatar
sam_marshall committed
231
232
/**
 * Class represents completion information for a course.
233
234
235
236
 *
 * Does not contain any data, so you can safely construct it multiple times
 * without causing any problems.
 *
237
238
239
 * @package core
 * @category completion
 * @copyright 2008 Sam Marshall
240
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
sam_marshall's avatar
sam_marshall committed
241
242
 */
class completion_info {
243

244
    /* @var stdClass Course object passed during construction */
sam_marshall's avatar
sam_marshall committed
245
    private $course;
skodak's avatar
skodak committed
246

247
    /* @var int Course id */
248
249
    public $course_id;

250
    /* @var array Completion criteria {@link completion_info::get_criteria()}  */
251
252
253
254
    private $criteria;

    /**
     * Return array of aggregation methods
255
     * @return array
256
257
258
     */
    public static function get_aggregation_methods() {
        return array(
259
260
            COMPLETION_AGGREGATION_ALL => get_string('all'),
            COMPLETION_AGGREGATION_ANY => get_string('any', 'completion'),
261
262
263
        );
    }

sam_marshall's avatar
sam_marshall committed
264
265
266
    /**
     * Constructs with course details.
     *
267
     * When instantiating a new completion info object you must provide a course
268
269
270
     * object with at least id, and enablecompletion properties. Property
     * cacherev is needed if you check completion of the current user since
     * it is used for cache validation.
271
272
     *
     * @param stdClass $course Moodle course object.
sam_marshall's avatar
sam_marshall committed
273
     */
274
    public function __construct($course) {
skodak's avatar
skodak committed
275
        $this->course = $course;
276
        $this->course_id = $course->id;
sam_marshall's avatar
sam_marshall committed
277
278
279
    }

    /**
280
     * Determines whether completion is enabled across entire site.
281
     *
282
     * @return bool COMPLETION_ENABLED (true) if completion is enabled for the site,
sam_marshall's avatar
sam_marshall committed
283
284
285
286
     *     COMPLETION_DISABLED (false) if it's complete
     */
    public static function is_enabled_for_site() {
        global $CFG;
287
        return !empty($CFG->enablecompletion);
sam_marshall's avatar
sam_marshall committed
288
    }
skodak's avatar
skodak committed
289

sam_marshall's avatar
sam_marshall committed
290
291
292
293
    /**
     * Checks whether completion is enabled in a particular course and possibly
     * activity.
     *
294
     * @param stdClass|cm_info $cm Course-module object. If not specified, returns the course
sam_marshall's avatar
sam_marshall committed
295
     *   completion enable state.
296
     * @return mixed COMPLETION_ENABLED or COMPLETION_DISABLED (==0) in the case of
sam_marshall's avatar
sam_marshall committed
297
298
299
     *   site and course; COMPLETION_TRACKING_MANUAL, _AUTOMATIC or _NONE (==0)
     *   for a course-module.
     */
300
    public function is_enabled($cm = null) {
301
        global $CFG, $DB;
skodak's avatar
skodak committed
302
303

        // First check global completion
304
        if (!isset($CFG->enablecompletion) || $CFG->enablecompletion == COMPLETION_DISABLED) {
sam_marshall's avatar
sam_marshall committed
305
306
            return COMPLETION_DISABLED;
        }
skodak's avatar
skodak committed
307

308
309
        // Load data if we do not have enough
        if (!isset($this->course->enablecompletion)) {
310
            $this->course = get_course($this->course_id);
311
312
        }

sam_marshall's avatar
sam_marshall committed
313
        // Check course completion
skodak's avatar
skodak committed
314
        if ($this->course->enablecompletion == COMPLETION_DISABLED) {
sam_marshall's avatar
sam_marshall committed
315
316
            return COMPLETION_DISABLED;
        }
skodak's avatar
skodak committed
317

sam_marshall's avatar
sam_marshall committed
318
        // If there was no $cm and we got this far, then it's enabled
skodak's avatar
skodak committed
319
        if (!$cm) {
sam_marshall's avatar
sam_marshall committed
320
321
            return COMPLETION_ENABLED;
        }
skodak's avatar
skodak committed
322

sam_marshall's avatar
sam_marshall committed
323
324
325
        // Return course-module completion value
        return $cm->completion;
    }
skodak's avatar
skodak committed
326

327
328
329
    /**
     * Displays the 'Your progress' help icon, if completion tracking is enabled.
     * Just prints the result of display_help_icon().
330
331
     *
     * @deprecated since Moodle 2.0 - Use display_help_icon instead.
332
333
     */
    public function print_help_icon() {
334
335
        debugging('The function print_help_icon() is deprecated, please do not use it anymore.',
            DEBUG_DEVELOPER);
336
337
338
        print $this->display_help_icon();
    }

339
    /**
340
     * Returns the 'Your progress' help icon, if completion tracking is enabled.
341
     *
342
     * @return string HTML code for help icon, or blank if not needed
343
     * @deprecated since Moodle 4.0 - The 'Your progress' info isn't displayed any more.
344
     */
345
    public function display_help_icon() {
346
        global $PAGE, $OUTPUT, $USER;
347
348
        debugging('The function display_help_icon() is deprecated, please do not use it anymore.',
        DEBUG_DEVELOPER);
349
        $result = '';
350
351
        if ($this->is_enabled() && !$PAGE->user_is_editing() && $this->is_tracked_user($USER->id) && isloggedin() &&
                !isguestuser()) {
352
353
354
            $result .= html_writer::tag('div', get_string('yourprogress','completion') .
                    $OUTPUT->help_icon('completionicons', 'completion'), array('id' => 'completionprogressid',
                    'class' => 'completionprogress'));
355
        }
356
        return $result;
357
    }
358
359
360

    /**
     * Get a course completion for a user
361
362
363
     *
     * @param int $user_id User id
     * @param int $criteriatype Specific criteria type to return
364
     * @return bool|completion_criteria_completion returns false on fail
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
     */
    public function get_completion($user_id, $criteriatype) {
        $completions = $this->get_completions($user_id, $criteriatype);

        if (empty($completions)) {
            return false;
        } elseif (count($completions) > 1) {
            print_error('multipleselfcompletioncriteria', 'completion');
        }

        return $completions[0];
    }

    /**
     * Get all course criteria's completion objects for a user
380
381
382
383
     *
     * @param int $user_id User id
     * @param int $criteriatype Specific criteria type to return (optional)
     * @return array
384
385
     */
    public function get_completions($user_id, $criteriatype = null) {
386
        $criteria = $this->get_criteria($criteriatype);
387
388
389

        $completions = array();

390
        foreach ($criteria as $criterion) {
391
392
393
            $params = array(
                'course'        => $this->course_id,
                'userid'        => $user_id,
394
                'criteriaid'    => $criterion->id
395
396
397
            );

            $completion = new completion_criteria_completion($params);
398
            $completion->attach_criteria($criterion);
399
400
401
402
403
404
405
406
407

            $completions[] = $completion;
        }

        return $completions;
    }

    /**
     * Get completion object for a user and a criteria
408
409
410
411
     *
     * @param int $user_id User id
     * @param completion_criteria $criteria Criteria object
     * @return completion_criteria_completion
412
413
414
     */
    public function get_user_completion($user_id, $criteria) {
        $params = array(
415
416
            'course'        => $this->course_id,
            'userid'        => $user_id,
417
418
419
420
421
422
423
424
425
426
            'criteriaid'    => $criteria->id,
        );

        $completion = new completion_criteria_completion($params);
        return $completion;
    }

    /**
     * Check if course has completion criteria set
     *
427
     * @return bool Returns true if there are criteria
428
429
430
431
432
433
434
435
436
     */
    public function has_criteria() {
        $criteria = $this->get_criteria();

        return (bool) count($criteria);
    }

    /**
     * Get course completion criteria
437
438
     *
     * @param int $criteriatype Specific criteria type to return (optional)
439
440
441
442
443
444
445
446
447
448
449
450
451
452
     */
    public function get_criteria($criteriatype = null) {

        // Fill cache if empty
        if (!is_array($this->criteria)) {
            global $DB;

            $params = array(
                'course'    => $this->course->id
            );

            // Load criteria from database
            $records = (array)$DB->get_records('course_completion_criteria', $params);

453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
            // Order records so activities are in the same order as they appear on the course view page.
            if ($records) {
                $activitiesorder = array_keys(get_fast_modinfo($this->course)->get_cms());
                usort($records, function ($a, $b) use ($activitiesorder) {
                    $aidx = ($a->criteriatype == COMPLETION_CRITERIA_TYPE_ACTIVITY) ?
                        array_search($a->moduleinstance, $activitiesorder) : false;
                    $bidx = ($b->criteriatype == COMPLETION_CRITERIA_TYPE_ACTIVITY) ?
                        array_search($b->moduleinstance, $activitiesorder) : false;
                    if ($aidx === false || $bidx === false || $aidx == $bidx) {
                        return 0;
                    }
                    return ($aidx < $bidx) ? -1 : 1;
                });
            }

468
469
470
            // Build array of criteria objects
            $this->criteria = array();
            foreach ($records as $record) {
471
                $this->criteria[$record->id] = completion_criteria::factory((array)$record);
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
            }
        }

        // If after all criteria
        if ($criteriatype === null) {
            return $this->criteria;
        }

        // If we are only after a specific criteria type
        $criteria = array();
        foreach ($this->criteria as $criterion) {

            if ($criterion->criteriatype != $criteriatype) {
                continue;
            }

            $criteria[$criterion->id] = $criterion;
        }

        return $criteria;
    }

    /**
     * Get aggregation method
496
497
498
     *
     * @param int $criteriatype If none supplied, get overall aggregation method (optional)
     * @return int One of COMPLETION_AGGREGATION_ALL or COMPLETION_AGGREGATION_ANY
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
     */
    public function get_aggregation_method($criteriatype = null) {
        $params = array(
            'course'        => $this->course_id,
            'criteriatype'  => $criteriatype
        );

        $aggregation = new completion_aggregation($params);

        if (!$aggregation->id) {
            $aggregation->method = COMPLETION_AGGREGATION_ALL;
        }

        return $aggregation->method;
    }

    /**
516
     * @deprecated since Moodle 2.8 MDL-46290.
517
518
     */
    public function get_incomplete_criteria() {
519
        throw new coding_exception('completion_info->get_incomplete_criteria() is removed.');
520
521
522
523
524
525
526
    }

    /**
     * Clear old course completion criteria
     */
    public function clear_criteria() {
        global $DB;
527
528
529
530
531
532
533
534
535
536

        // Remove completion criteria records for the course itself, and any records that refer to the course.
        $select = 'course = :course OR (criteriatype = :type AND courseinstance = :courseinstance)';
        $params = [
            'course' => $this->course_id,
            'type' => COMPLETION_CRITERIA_TYPE_COURSE,
            'courseinstance' => $this->course_id,
        ];

        $DB->delete_records_select('course_completion_criteria', $select, $params);
537
538
539
540
541
542
543
        $DB->delete_records('course_completion_aggr_methd', array('course' => $this->course_id));

        $this->delete_course_completion_data();
    }

    /**
     * Has the supplied user completed this course
544
545
546
     *
     * @param int $user_id User's id
     * @return boolean
547
548
549
550
551
552
553
554
555
556
557
     */
    public function is_course_complete($user_id) {
        $params = array(
            'userid'    => $user_id,
            'course'  => $this->course_id
        );

        $ccompletion = new completion_completion($params);
        return $ccompletion->is_complete();
    }

558
559
560
561
562
563
564
565
566
567
    /**
     * Check whether the supplied user can override the activity completion statuses within the current course.
     *
     * @param stdClass $user The user object.
     * @return bool True if the user can override, false otherwise.
     */
    public function user_can_override_completion($user) {
        return has_capability('moodle/course:overridecompletion', context_course::instance($this->course_id), $user);
    }

sam_marshall's avatar
sam_marshall committed
568
569
570
    /**
     * Updates (if necessary) the completion state of activity $cm for the given
     * user.
571
     *
sam_marshall's avatar
sam_marshall committed
572
573
     * For manual completion, this function is called when completion is toggled
     * with $possibleresult set to the target state.
574
     *
sam_marshall's avatar
sam_marshall committed
575
576
577
578
579
     * For automatic completion, this function should be called every time a module
     * does something which might influence a user's completion state. For example,
     * if a forum provides options for marking itself 'completed' once a user makes
     * N posts, this function should be called every time a user makes a new post.
     * [After the post has been saved to the database]. When calling, you do not
580
581
582
583
     * need to pass in the new completion state. Instead this function carries out completion
     * calculation by checking grades and viewed state itself, and calling the involved module
     * via mod_{modulename}\\completion\\custom_completion::get_overall_completion_state() to
     * check module-specific conditions.
sam_marshall's avatar
sam_marshall committed
584
     *
585
     * @param stdClass|cm_info $cm Course-module
sam_marshall's avatar
sam_marshall committed
586
587
588
589
590
591
592
593
594
595
596
     * @param int $possibleresult Expected completion result. If the event that
     *   has just occurred (e.g. add post) can only result in making the activity
     *   complete when it wasn't before, use COMPLETION_COMPLETE. If the event that
     *   has just occurred (e.g. delete post) can only result in making the activity
     *   not complete when it was previously complete, use COMPLETION_INCOMPLETE.
     *   Otherwise use COMPLETION_UNKNOWN. Setting this value to something other than
     *   COMPLETION_UNKNOWN significantly improves performance because it will abandon
     *   processing early if the user's completion state already matches the expected
     *   result. For manual events, COMPLETION_COMPLETE or COMPLETION_INCOMPLETE
     *   must be used; these directly set the specified state.
     * @param int $userid User ID to be updated. Default 0 = current user
597
     * @param bool $override Whether manually overriding the existing completion state.
598
     * @param bool $isbulkupdate If bulk grade update is happening.
599
     * @return void
600
     * @throws moodle_exception if trying to override without permission.
sam_marshall's avatar
sam_marshall committed
601
     */
602
603
    public function update_state($cm, $possibleresult=COMPLETION_UNKNOWN, $userid=0,
            $override = false, $isbulkupdate = false) {
604
        global $USER;
skodak's avatar
skodak committed
605

skodak's avatar
skodak committed
606
607
        // Do nothing if completion is not enabled for that activity
        if (!$this->is_enabled($cm)) {
sam_marshall's avatar
sam_marshall committed
608
609
            return;
        }
skodak's avatar
skodak committed
610

611
612
613
614
615
616
617
618
        // If we're processing an override and the current user isn't allowed to do so, then throw an exception.
        if ($override) {
            if (!$this->user_can_override_completion($USER)) {
                throw new required_capability_exception(context_course::instance($this->course_id),
                                                        'moodle/course:overridecompletion', 'nopermission', '');
            }
        }

619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
        // Default to current user if one is not provided.
        if ($userid == 0) {
            $userid = $USER->id;
        }

        // Delete the cm's cached completion data for this user if automatic completion is enabled.
        // This ensures any changes to the status of individual completion conditions in the activity will be fetched.
        if ($cm->completion == COMPLETION_TRACKING_AUTOMATIC) {
            $completioncache = cache::make('core', 'completion');
            $completionkey = $userid . '_' . $this->course->id;
            $completiondata = $completioncache->get($completionkey);

            if ($completiondata !== false) {
                unset($completiondata[$cm->id]);
                $completioncache->set($completionkey, $completiondata);
            }
        }

sam_marshall's avatar
sam_marshall committed
637
638
639
        // Get current value of completion state and do nothing if it's same as
        // the possible result of this change. If the change is to COMPLETE and the
        // current value is one of the COMPLETE_xx subtypes, ignore that as well
skodak's avatar
skodak committed
640
641
642
643
644
        $current = $this->get_data($cm, false, $userid);
        if ($possibleresult == $current->completionstate ||
            ($possibleresult == COMPLETION_COMPLETE &&
                ($current->completionstate == COMPLETION_COMPLETE_PASS ||
                $current->completionstate == COMPLETION_COMPLETE_FAIL))) {
sam_marshall's avatar
sam_marshall committed
645
646
            return;
        }
skodak's avatar
skodak committed
647

648
649
650
651
652
653
654
655
656
657
        // For auto tracking, if the status is overridden to 'COMPLETION_COMPLETE', then disallow further changes,
        // unless processing another override.
        // Basically, we want those activities which have been overridden to COMPLETE to hold state, and those which have been
        // overridden to INCOMPLETE to still be processed by normal completion triggers.
        if ($cm->completion == COMPLETION_TRACKING_AUTOMATIC && !is_null($current->overrideby)
            && $current->completionstate == COMPLETION_COMPLETE && !$override) {
            return;
        }

        // For manual tracking, or if overriding the completion state, we set the state directly.
658
        if ($cm->completion == COMPLETION_TRACKING_MANUAL || $override) {
sam_marshall's avatar
sam_marshall committed
659
660
661
            switch($possibleresult) {
                case COMPLETION_COMPLETE:
                case COMPLETION_INCOMPLETE:
skodak's avatar
skodak committed
662
                    $newstate = $possibleresult;
sam_marshall's avatar
sam_marshall committed
663
664
665
666
                    break;
                default:
                    $this->internal_systemerror("Unexpected manual completion state for {$cm->id}: $possibleresult");
            }
skodak's avatar
skodak committed
667

sam_marshall's avatar
sam_marshall committed
668
        } else {
669
            $newstate = $this->internal_get_state($cm, $userid, $current);
sam_marshall's avatar
sam_marshall committed
670
        }
skodak's avatar
skodak committed
671

672
        // If the overall completion state has changed, update it in the cache.
skodak's avatar
skodak committed
673
674
675
        if ($newstate != $current->completionstate) {
            $current->completionstate = $newstate;
            $current->timemodified    = time();
676
            $current->overrideby      = $override ? $USER->id : null;
677
            $this->internal_set_data($cm, $current, $isbulkupdate);
sam_marshall's avatar
sam_marshall committed
678
679
        }
    }
skodak's avatar
skodak committed
680

sam_marshall's avatar
sam_marshall committed
681
682
683
    /**
     * Calculates the completion state for an activity and user.
     *
684
     * Internal function. Not private, so we can unit-test it.
685
     *
686
     * @param stdClass|cm_info $cm Activity
sam_marshall's avatar
sam_marshall committed
687
     * @param int $userid ID of user
688
     * @param stdClass $current Previous completion information from database
689
     * @return mixed
sam_marshall's avatar
sam_marshall committed
690
     */
691
    public function internal_get_state($cm, $userid, $current) {
692
        global $USER, $DB;
skodak's avatar
skodak committed
693
694

        // Get user ID
skodak's avatar
skodak committed
695
696
        if (!$userid) {
            $userid = $USER->id;
sam_marshall's avatar
sam_marshall committed
697
        }
skodak's avatar
skodak committed
698

699
700
701
702
703
704
705
        $newstate = COMPLETION_COMPLETE;
        $completionstate = [];
        if ($cm->completionview == COMPLETION_VIEW_REQUIRED) {
            $newstate = ($current->viewed == COMPLETION_VIEWED ? COMPLETION_COMPLETE : COMPLETION_INCOMPLETE);
            $completionstate = [
                'viewed' => $newstate
            ];
sam_marshall's avatar
sam_marshall committed
706
        }
skodak's avatar
skodak committed
707

708
709
710
711
712
713
714
715
716
        if ($cm instanceof stdClass) {
            // Modname hopefully is provided in $cm but just in case it isn't, let's grab it.
            if (!isset($cm->modname)) {
                $cm->modname = $DB->get_field('modules', 'name', array('id' => $cm->module));
            }
            // Some functions call this method and pass $cm as an object with ID only. Make sure course is set as well.
            if (!isset($cm->course)) {
                $cm->course = $this->course_id;
            }
sam_marshall's avatar
sam_marshall committed
717
        }
718
719
        // Make sure we're using a cm_info object.
        $cminfo = cm_info::create($cm, $userid);
skodak's avatar
skodak committed
720

sam_marshall's avatar
sam_marshall committed
721
        // Check grade
722
723
        if (!is_null($cminfo->completiongradeitemnumber)) {
            $newstate = $this->get_grade_completion($cminfo, $userid);
724
            $completionstate['usegrade'] = $newstate;
725
            if ($cm->completionpassgrade) {
726
                // If we are asking to use pass grade completion but haven't set it properly,
727
728
                // then default to COMPLETION_COMPLETE_PASS.
                if ($newstate == COMPLETION_COMPLETE) {
729
730
731
732
733
734
735
                    $newstate = COMPLETION_COMPLETE_PASS;
                }

                // The criteria is to mark an activity as complete if a passing grade has been achieved.
                // COMPLETION_COMPLETE_FAIL still marks the activity as completed which is incorrect.
                // Rectify this.
                if ($newstate == COMPLETION_COMPLETE_FAIL) {
736
737
                    $newstate = COMPLETION_INCOMPLETE;
                }
738
739

                $completionstate['passgrade'] = $newstate;
sam_marshall's avatar
sam_marshall committed
740
741
            }
        }
skodak's avatar
skodak committed
742

743
        if (plugin_supports('mod', $cminfo->modname, FEATURE_COMPLETION_HAS_RULES)) {
744
            $response = true;
745
746
747
748
            $cmcompletionclass = activity_custom_completion::get_cm_completion_class($cminfo->modname);
            if ($cmcompletionclass) {
                /** @var activity_custom_completion $cmcompletion */
                $cmcompletion = new $cmcompletionclass($cminfo, $userid);
749
                $response = $cmcompletion->get_overall_completion_state() != COMPLETION_INCOMPLETE;
750
751
            } else {
                // Fallback to the get_completion_state callback.
752
                $cmcompletionclass = "mod_{$cminfo->modname}\\completion\\custom_completion";
753
754
                $function = $cminfo->modname . '_get_completion_state';
                if (!function_exists($function)) {
755
756
757
                    $this->internal_systemerror("Module {$cminfo->modname} claims to support FEATURE_COMPLETION_HAS_RULES " .
                        "but does not implement the custom completion class $cmcompletionclass which extends " .
                        "\core_completion\activity_custom_completion.");
758
                }
759
760
761
                debugging("*_get_completion_state() callback functions such as $function have been deprecated and should no " .
                    "longer be used. Please implement the custom completion class $cmcompletionclass which extends " .
                    "\core_completion\activity_custom_completion.", DEBUG_DEVELOPER);
762
                $response = $function($this->course, $cm, $userid, COMPLETION_AND, $completionstate);
sam_marshall's avatar
sam_marshall committed
763
            }
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789

            // Get the relationship between the core_completion and plugin_completion criteria.
            $aggregationtype = COMPLETION_STANDARD_FLOW;
            if ($aggregationfn = component_callback_exists("mod_$cminfo->modname", 'get_completion_aggregation_state')) {
                $aggregationtype = $aggregationfn();
            }
            // If the module aggregates using COMPLETION_STANDARD_FLOW, it requires ALL conditions to be met.
            // If the aggregation type is COMPLETION_CUSTOM_MODULE_FLOW, completion can be overridden by the plugin.
            if (!$response && $aggregationtype == COMPLETION_STANDARD_FLOW) {
                return COMPLETION_INCOMPLETE;
            } else if ($aggregationtype == COMPLETION_CUSTOM_MODULE_FLOW) {
                return ($response ? COMPLETION_COMPLETE : COMPLETION_INCOMPLETE);
            }
        }

        if ($completionstate) {
            // We have allowed the plugins to do it's thing and run their own checks.
            // We have now reached a state where we need to AND all the calculated results.
            $newstate = array_reduce($completionstate, function($carry, $value) {
                if ($carry == COMPLETION_INCOMPLETE) {
                    return $carry;
                } else {
                    return $value;
                }

            }, COMPLETION_COMPLETE);
sam_marshall's avatar
sam_marshall committed
790
        }
skodak's avatar
skodak committed
791

sam_marshall's avatar
sam_marshall committed
792
        return $newstate;
skodak's avatar
skodak committed
793

sam_marshall's avatar
sam_marshall committed
794
    }
skodak's avatar
skodak committed
795

796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
    /**
     * Fetches the completion state for an activity completion's require grade completion requirement.
     *
     * @param cm_info $cm The course module information.
     * @param int $userid The user ID.
     * @return int The completion state.
     */
    public function get_grade_completion(cm_info $cm, int $userid): int {
        global $CFG;

        require_once($CFG->libdir . '/gradelib.php');
        $item = grade_item::fetch([
            'courseid' => $cm->course,
            'itemtype' => 'mod',
            'itemmodule' => $cm->modname,
            'iteminstance' => $cm->instance,
            'itemnumber' => $cm->completiongradeitemnumber
        ]);
        if ($item) {
            // Fetch 'grades' (will be one or none).
            $grades = grade_grade::fetch_users_grades($item, [$userid], false);
            if (empty($grades)) {
                // No grade for user.
                return COMPLETION_INCOMPLETE;
            }
            if (count($grades) > 1) {
                $this->internal_systemerror("Unexpected result: multiple grades for
                        item '{$item->id}', user '{$userid}'");
            }
            return self::internal_get_grade_state($item, reset($grades));
        }

        return COMPLETION_INCOMPLETE;
    }

sam_marshall's avatar
sam_marshall committed
831
832
    /**
     * Marks a module as viewed.
833
     *
sam_marshall's avatar
sam_marshall committed
834
835
836
     * Should be called whenever a module is 'viewed' (it is up to the module how to
     * determine that). Has no effect if viewing is not set as a completion condition.
     *
837
838
839
     * Note that this function must be called before you print the page header because
     * it is possible that the navigation block may depend on it. If you call it after
     * printing the header, it shows a developer debug warning.
840
841
     *
     * @param stdClass|cm_info $cm Activity
sam_marshall's avatar
sam_marshall committed
842
     * @param int $userid User ID or 0 (default) for current user
843
     * @return void
sam_marshall's avatar
sam_marshall committed
844
     */
skodak's avatar
skodak committed
845
    public function set_module_viewed($cm, $userid=0) {
846
847
        global $PAGE;
        if ($PAGE->headerprinted) {
848
849
850
            debugging('set_module_viewed must be called before header is printed',
                    DEBUG_DEVELOPER);
        }
851

sam_marshall's avatar
sam_marshall committed
852
        // Don't do anything if view condition is not turned on
skodak's avatar
skodak committed
853
        if ($cm->completionview == COMPLETION_VIEW_NOT_REQUIRED || !$this->is_enabled($cm)) {
sam_marshall's avatar
sam_marshall committed
854
855
            return;
        }
856

sam_marshall's avatar
sam_marshall committed
857
        // Get current completion state
858
859
        $data = $this->get_data($cm, false, $userid);

860
861
862
        // If we already viewed it, don't do anything unless the completion status is overridden.
        // If the completion status is overridden, then we need to allow this 'view' to trigger automatic completion again.
        if ($data->viewed == COMPLETION_VIEWED && empty($data->overrideby)) {
sam_marshall's avatar
sam_marshall committed
863
864
            return;
        }
865

sam_marshall's avatar
sam_marshall committed
866
        // OK, change state, save it, and update completion
skodak's avatar
skodak committed
867
868
869
        $data->viewed = COMPLETION_VIEWED;
        $this->internal_set_data($cm, $data);
        $this->update_state($cm, COMPLETION_COMPLETE, $userid);
sam_marshall's avatar
sam_marshall committed
870
    }
skodak's avatar
skodak committed
871

sam_marshall's avatar
sam_marshall committed
872
873
874
875
876
    /**
     * Determines how much completion data exists for an activity. This is used when
     * deciding whether completion information should be 'locked' in the module
     * editing form.
     *
877
     * @param cm_info $cm Activity
sam_marshall's avatar
sam_marshall committed
878
     * @return int The number of users who have completion data stored for this
skodak's avatar
skodak committed
879
     *   activity, 0 if none
sam_marshall's avatar
sam_marshall committed
880
881
     */
    public function count_user_data($cm) {
882
        global $DB;
skodak's avatar
skodak committed
883

sam_marshall's avatar
sam_marshall committed
884
885
886
887
        return $DB->get_field_sql("
    SELECT
        COUNT(1)
    FROM
888
        {course_modules_completion}
sam_marshall's avatar
sam_marshall committed
889
    WHERE
skodak's avatar
skodak committed
890
        coursemoduleid=? AND completionstate<>0", array($cm->id));
sam_marshall's avatar
sam_marshall committed
891
    }
skodak's avatar
skodak committed
892

893
894
895
896
897
    /**
     * Determines how much course completion data exists for a course. This is used when
     * deciding whether completion information should be 'locked' in the completion
     * settings form and activity completion settings.
     *
898
     * @param int $user_id Optionally only get course completion data for a single user
899
     * @return int The number of users who have completion data stored for this
900
     *     course, 0 if none
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
     */
    public function count_course_user_data($user_id = null) {
        global $DB;

        $sql = '
    SELECT
        COUNT(1)
    FROM
        {course_completion_crit_compl}
    WHERE
        course = ?
        ';

        $params = array($this->course_id);

        // Limit data to a single user if an ID is supplied
        if ($user_id) {
            $sql .= ' AND userid = ?';
            $params[] = $user_id;
        }

        return $DB->get_field_sql($sql, $params);
    }

    /**
     * Check if this course's completion criteria should be locked
     *
928
     * @return boolean
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
     */
    public function is_course_locked() {
        return (bool) $this->count_course_user_data();
    }

    /**
     * Deletes all course completion completion data.
     *
     * Intended to be used when unlocking completion criteria settings.
     */
    public function delete_course_completion_data() {
        global $DB;

        $DB->delete_records('course_completions', array('course' => $this->course_id));
        $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id));
944
945
946

        // Difficult to find affected users, just purge all completion cache.
        cache::make('core', 'completion')->purge();
947
        cache::make('core', 'coursecompletion')->purge();
948
949
    }

950
951
952
953
954
955
956
    /**
     * Deletes all activity and course completion data for an entire course
     * (the below delete_all_state function does this for a single activity).
     *
     * Used by course reset page.
     */
    public function delete_all_completion_data() {
957
        global $DB;
958
959
960
961
962
963
964
965
966
967

        // Delete from database.
        $DB->delete_records_select('course_modules_completion',
                'coursemoduleid IN (SELECT id FROM {course_modules} WHERE course=?)',
                array($this->course_id));

        // Wipe course completion data too.
        $this->delete_course_completion_data();
    }

sam_marshall's avatar
sam_marshall committed
968
    /**
skodak's avatar
skodak committed
969
     * Deletes completion state related to an activity for all users.
970
     *
sam_marshall's avatar
sam_marshall committed
971
972
     * Intended for use only when the activity itself is deleted.
     *
973
     * @param stdClass|cm_info $cm Activity
sam_marshall's avatar
sam_marshall committed
974
     */
skodak's avatar
skodak committed
975
    public function delete_all_state($cm) {
976
        global $DB;
skodak's avatar
skodak committed
977

sam_marshall's avatar
sam_marshall committed
978
        // Delete from database
skodak's avatar
skodak committed
979
980
        $DB->delete_records('course_modules_completion', array('coursemoduleid'=>$cm->id));

981
982
983
984
985
986
987
        // Check if there is an associated course completion criteria
        $criteria = $this->get_criteria(COMPLETION_CRITERIA_TYPE_ACTIVITY);
        $acriteria = false;
        foreach ($criteria as $criterion) {
            if ($criterion->moduleinstance == $cm->id) {
                $acriteria = $criterion;
                break;
988
            }
989
990
991
992
993
994
995
        }

        if ($acriteria) {
            // Delete all criteria completions relating to this activity
            $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id, 'criteriaid' => $acriteria->id));
            $DB->delete_records('course_completions', array('course' => $this->course_id));
        }
996
997
998

        // Difficult to find affected users, just purge all completion cache.
        cache::make('core', 'completion')->purge();
999
        cache::make('core', 'coursecompletion')->purge();
sam_marshall's avatar
sam_marshall committed
1000
    }
skodak's avatar
skodak committed
1001

sam_marshall's avatar
sam_marshall committed
1002
1003
    /**
     * Recalculates completion state related to an activity for all users.
1004
     *
sam_marshall's avatar
sam_marshall committed
1005
1006
1007
1008
     * Intended for use if completion conditions change. (This should be avoided
     * as it may cause some things to become incomplete when they were previously
     * complete, with the effect - for example - of hiding a later activity that
     * was previously available.)
1009
     *
skodak's avatar
skodak committed
1010
     * Resetting state of manual tickbox has same result as deleting state for
1011
     * it.
1012
     *
1013
     * @param stcClass|cm_info $cm Activity
sam_marshall's avatar
sam_marshall committed
1014
1015
     */
    public function reset_all_state($cm) {
skodak's avatar
skodak committed
1016
1017
        global $DB;

skodak's avatar
skodak committed
1018
        if ($cm->completion == COMPLETION_TRACKING_MANUAL) {
1019
1020
1021
            $this->delete_all_state($cm);
            return;
        }
sam_marshall's avatar
sam_marshall committed
1022
        // Get current list of users with completion state
skodak's avatar
skodak committed
1023
1024
1025
1026
        $rs = $DB->get_recordset('course_modules_completion', array('coursemoduleid'=>$cm->id), '', 'userid');
        $keepusers = array();
        foreach ($rs as $rec) {
            $keepusers[] = $rec->userid;
sam_marshall's avatar
sam_marshall committed
1027
1028
        }
        $rs->close();
skodak's avatar
skodak committed
1029

1030
        // Delete all existing state.
sam_marshall's avatar
sam_marshall committed
1031
        $this->delete_all_state($cm);
skodak's avatar
skodak committed
1032
1033

        // Merge this with list of planned users (according to roles)
1034
        $trackedusers = $this->get_tracked_users();
skodak's avatar
skodak committed
1035
1036
1037
1038
1039
        foreach ($trackedusers as $trackeduser) {
            $keepusers[] = $trackeduser->id;
        }
        $keepusers = array_unique($keepusers);

sam_marshall's avatar
sam_marshall committed
1040
        // Recalculate state for each kept user
skodak's avatar
skodak committed
1041
1042
        foreach ($keepusers as $keepuser) {
            $this->update_state($cm, COMPLETION_UNKNOWN, $keepuser);
sam_marshall's avatar
sam_marshall committed
1043
1044
        }
    }
skodak's avatar
skodak committed
1045

sam_marshall's avatar
sam_marshall committed
1046
1047
    /**
     * Obtains completion data for a particular activity and user (from the
1048
     * completion cache if available, or by SQL query)
sam_marshall's avatar
sam_marshall committed
1049
     *
1050
     * @param stdClass|cm_info $cm Activity; only required field is ->id
sam_marshall's avatar
sam_marshall committed
1051
1052
1053
1054
     * @param bool $wholecourse If true (default false) then, when necessary to
     *   fill the cache, retrieves information from the entire course not just for
     *   this one activity
     * @param int $userid User ID or 0 (default) for current user
1055
1056
     * @param array $modinfo Supply the value here - this is used for unit
     *   testing and so that it can be called recursively from within
1057
1058
     *   get_fast_modinfo. (Needs only list of all CMs with IDs.)
     *   Otherwise the method calls get_fast_modinfo itself.
1059
1060
1061
     * @return object Completion data. Record from course_modules_completion plus other completion statuses such as
     *                  - Completion status for 'must-receive-grade' completion rule.
     *                  - Custom completion statuses defined by the activity module plugin.
sam_marshall's avatar
sam_marshall committed
1062
     */
1063
    public function get_data($cm, $wholecourse = false, $userid = 0, $modinfo = null) {
1064
        global $USER, $DB;
1065
        $completioncache = cache::make('core', 'completion');
skodak's avatar
skodak committed
1066
1067

        // Get user ID
skodak's avatar
skodak committed
1068
1069
        if (!$userid) {
            $userid = $USER->id;
sam_marshall's avatar
sam_marshall committed
1070
        }
skodak's avatar
skodak committed
1071

1072
1073
1074
1075
        // See if requested data is present in cache (use cache for current user only).
        $usecache = $userid == $USER->id;
        $cacheddata = array();
        if ($usecache) {
1076
            $key = $userid . '_' . $this->course->id;
1077
1078
1079
            if (!isset($this->course->cacherev)) {
                $this->course = get_course($this->course_id);
            }
1080
            if ($cacheddata = $completioncache->get($key)) {
1081
1082
1083
                if ($cacheddata['cacherev'] != $this->course->cacherev) {
                    // Course structure has been changed since the last caching, forget the cache.
                    $cacheddata = array();
1084
1085
                } else if (isset($cacheddata[$cm->id])) {
                    return (object)$cacheddata[$cm->id];
1086
1087
                }
            }
sam_marshall's avatar
sam_marshall committed
1088
        }
skodak's avatar
skodak committed
1089

1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
        // Some call completion_info::get_data and pass $cm as an object with ID only. Make sure course is set as well.
        if ($cm instanceof stdClass && !isset($cm->course)) {
            $cm->course = $this->course_id;
        }
        // Make sure we're working on a cm_info object.
        $cminfo = cm_info::create($cm, $userid);

        // Default data to return when no completion data is found.
        $defaultdata = [
            'id' => 0,
            'coursemoduleid' => $cminfo->id,
            'userid' => $userid,
            'completionstate' => 0,
            'viewed' => 0,
            'overrideby' => null,
            'timemodified' => 0,
        ];

        // If cached completion data is not found, fetch via SQL.
        // Fetch completion data for all of the activities in the course ONLY if we're caching the fetched completion data.
        // If we're not caching the completion data, then just fetch the completion data for the user in this course module.
1111
        if ($usecache && $wholecourse) {
1112
1113
1114
1115
1116
1117
1118
1119
            // Get whole course data for cache.
            $alldatabycmc = $DB->get_records_sql("SELECT cm.id AS cmid, cmc.*
                                                    FROM {course_modules} cm
                                               LEFT JOIN {course_modules_completion} cmc ON cmc.coursemoduleid = cm.id
                                                         AND cmc.userid = ?
                                              INNER JOIN {modules} m ON m.id = cm.module
                                                   WHERE m.visible = 1 AND cm.course = ?", [$userid, $this->course->id]);

1120
1121
            $cminfos = get_fast_modinfo($cm->course, $userid)->get_cms();

1122
            // Reindex by course module id.
1123
            foreach ($alldatabycmc as $data) {
1124
1125
1126
1127
1128
1129

                // Filter acitivites with no cm_info (missing plugins or other causes).
                if (!isset($cminfos[$data->cmid])) {
                    continue;
                }

1130
1131
1132
                if (empty($data->coursemoduleid)) {
                    $cacheddata[$data->cmid] = $defaultdata;
                    $cacheddata[$data->cmid]['coursemoduleid'] = $data->cmid;
sam_marshall's avatar
sam_marshall committed
1133
                } else {
1134
                    $cacheddata[$data->cmid] = (array) $data;
sam_marshall's avatar
sam_marshall committed
1135
                }
1136

1137
                // Add the other completion data for this user in this module instance.
1138
                $othercminfo = $cminfos[$data->cmid];
1139
                $cacheddata[$othercminfo->id] += $this->get_other_cm_completion_data($othercminfo, $userid);
sam_marshall's avatar
sam_marshall committed
1140
            }
skodak's avatar
skodak committed
1141

1142
1143
1144
            if (!isset($cacheddata[$cminfo->id])) {
                $errormessage = "Unexpected error: course-module {$cminfo->id} could not be found on course {$this->course->id}";
                $this->internal_systemerror($errormessage);
sam_marshall's avatar
sam_marshall committed
1145
            }
skodak's avatar
skodak committed
1146

sam_marshall's avatar
sam_marshall committed
1147
1148
        } else {
            // Get single record
1149
            $data = $DB->get_record('course_modules_completion', array('coursemoduleid' => $cminfo->id, 'userid' => $userid));
1150
1151
1152
            if ($data) {
                $data = (array)$data;
            } else {
1153
1154
                // Row not present counts as 'not complete'.
                $data = $defaultdata;
sam_marshall's avatar
sam_marshall committed
1155
            }
1156
1157
            // Fill the other completion data for this user in this module instance.
            $data += $this->get_other_cm_completion_data($cminfo, $userid);
skodak's avatar
skodak committed
1158

sam_marshall's avatar
sam_marshall committed
1159
            // Put in cache
1160
            $cacheddata[$cminfo->id] = $data;
sam_marshall's avatar
sam_marshall committed
1161
        }
skodak's avatar
skodak committed
1162

1163
1164
        if ($usecache) {
            $cacheddata['cacherev'] = $this->course->cacherev;
1165
            $completioncache->set($key, $cacheddata);
1166
        }
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
        return (object)$cacheddata[$cminfo->id];
    }

    /**
     * Adds the user's custom completion data on the given course module.
     *
     * @param cm_info $cm The course module information.
     * @param int $userid The user ID.
     * @return