Proyectos de Subversion Moodle

Rev

Rev 11 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
/**
18
 * Contains classes, functions and constants used during the tracking
19
 * of activity completion for users.
20
 *
21
 * Completion top-level options (admin setting enablecompletion)
22
 *
23
 * @package core_completion
24
 * @category completion
25
 * @copyright 1999 onwards Martin Dougiamas   {@link http://moodle.com}
26
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27
 */
28
 
29
use core_completion\activity_custom_completion;
30
use core_courseformat\base as course_format;
31
 
32
defined('MOODLE_INTERNAL') || die();
33
 
34
/**
35
 * Include the required completion libraries
36
 */
37
require_once $CFG->dirroot.'/completion/completion_aggregation.php';
38
require_once $CFG->dirroot.'/completion/criteria/completion_criteria.php';
39
require_once $CFG->dirroot.'/completion/completion_completion.php';
40
require_once $CFG->dirroot.'/completion/completion_criteria_completion.php';
41
 
42
 
43
/**
44
 * The completion system is enabled in this site/course
45
 */
46
define('COMPLETION_ENABLED', 1);
47
/**
48
 * The completion system is not enabled in this site/course
49
 */
50
define('COMPLETION_DISABLED', 0);
51
 
52
/**
53
 * Completion tracking is disabled for this activity
54
 * This is a completion tracking option per-activity  (course_modules/completion)
55
 */
56
define('COMPLETION_TRACKING_NONE', 0);
57
 
58
/**
59
 * Manual completion tracking (user ticks box) is enabled for this activity
60
 * This is a completion tracking option per-activity  (course_modules/completion)
61
 */
62
define('COMPLETION_TRACKING_MANUAL', 1);
63
/**
64
 * Automatic completion tracking (system ticks box) is enabled for this activity
65
 * This is a completion tracking option per-activity  (course_modules/completion)
66
 */
67
define('COMPLETION_TRACKING_AUTOMATIC', 2);
68
 
69
/**
70
 * The user has not completed this activity.
71
 * This is a completion state value (course_modules_completion/completionstate)
72
 */
73
define('COMPLETION_INCOMPLETE', 0);
74
/**
75
 * The user has completed this activity. It is not specified whether they have
76
 * passed or failed it.
77
 * This is a completion state value (course_modules_completion/completionstate)
78
 */
79
define('COMPLETION_COMPLETE', 1);
80
/**
81
 * The user has completed this activity with a grade above the pass mark.
82
 * This is a completion state value (course_modules_completion/completionstate)
83
 */
84
define('COMPLETION_COMPLETE_PASS', 2);
85
/**
86
 * The user has completed this activity but their grade is less than the pass mark
87
 * This is a completion state value (course_modules_completion/completionstate)
88
 */
89
define('COMPLETION_COMPLETE_FAIL', 3);
90
 
91
/**
92
 * Indicates that the user has received a failing grade for a hidden grade item.
93
 */
94
define('COMPLETION_COMPLETE_FAIL_HIDDEN', 4);
95
 
96
/**
97
 * The effect of this change to completion status is unknown.
98
 * A completion effect changes (used only in update_state)
99
 */
100
define('COMPLETION_UNKNOWN', -1);
101
/**
102
 * The user's grade has changed, so their new state might be
103
 * COMPLETION_COMPLETE_PASS or COMPLETION_COMPLETE_FAIL.
104
 * A completion effect changes (used only in update_state)
105
 */
106
define('COMPLETION_GRADECHANGE', -2);
107
 
108
/**
109
 * User must view this activity.
110
 * Whether view is required to create an activity (course_modules/completionview)
111
 */
112
define('COMPLETION_VIEW_REQUIRED', 1);
113
/**
114
 * User does not need to view this activity
115
 * Whether view is required to create an activity (course_modules/completionview)
116
 */
117
define('COMPLETION_VIEW_NOT_REQUIRED', 0);
118
 
119
/**
120
 * User has viewed this activity.
121
 * Completion viewed state (course_modules_completion/viewed)
122
 */
123
define('COMPLETION_VIEWED', 1);
124
/**
125
 * User has not viewed this activity.
126
 * Completion viewed state (course_modules_completion/viewed)
127
 */
128
define('COMPLETION_NOT_VIEWED', 0);
129
 
130
/**
131
 * Completion details should be ORed together and you should return false if
132
 * none apply.
133
 */
134
define('COMPLETION_OR', false);
135
/**
136
 * Completion details should be ANDed together and you should return true if
137
 * none apply
138
 */
139
define('COMPLETION_AND', true);
140
 
141
/**
142
 * Course completion criteria aggregation method.
143
 */
144
define('COMPLETION_AGGREGATION_ALL', 1);
145
/**
146
 * Course completion criteria aggregation method.
147
 */
148
define('COMPLETION_AGGREGATION_ANY', 2);
149
 
150
/**
151
 * Completion conditions will be displayed to user.
152
 */
153
define('COMPLETION_SHOW_CONDITIONS', 1);
154
 
155
/**
156
 * Completion conditions will be hidden from user.
157
 */
158
define('COMPLETION_HIDE_CONDITIONS', 0);
159
 
160
/**
161
 * Utility function for checking if the logged in user can view
162
 * another's completion data for a particular course
163
 *
164
 * @access  public
165
 * @param   int         $userid     Completion data's owner
166
 * @param   mixed       $course     Course object or Course ID (optional)
167
 * @return  boolean
168
 */
169
function completion_can_view_data($userid, $course = null) {
170
    global $USER;
171
 
172
    if (!isloggedin()) {
173
        return false;
174
    }
175
 
176
    if (!is_object($course)) {
177
        $cid = $course;
178
        $course = new stdClass();
179
        $course->id = $cid;
180
    }
181
 
182
    // Check if this is the site course
183
    if ($course->id == SITEID) {
184
        $course = null;
185
    }
186
 
187
    // Check if completion is enabled
188
    if ($course) {
189
        $cinfo = new completion_info($course);
190
        if (!$cinfo->is_enabled()) {
191
            return false;
192
        }
193
    } else {
194
        if (!completion_info::is_enabled_for_site()) {
195
            return false;
196
        }
197
    }
198
 
199
    // Is own user's data?
200
    if ($USER->id == $userid) {
201
        return true;
202
    }
203
 
204
    // Check capabilities
205
    $personalcontext = context_user::instance($userid);
206
 
207
    if (has_capability('moodle/user:viewuseractivitiesreport', $personalcontext)) {
208
        return true;
209
    } elseif (has_capability('report/completion:view', $personalcontext)) {
210
        return true;
211
    }
212
 
213
    if ($course->id) {
214
        $coursecontext = context_course::instance($course->id);
215
    } else {
216
        $coursecontext = context_system::instance();
217
    }
218
 
219
    if (has_capability('report/completion:view', $coursecontext)) {
220
        return true;
221
    }
222
 
223
    return false;
224
}
225
 
226
 
227
/**
228
 * Class represents completion information for a course.
229
 *
230
 * Does not contain any data, so you can safely construct it multiple times
231
 * without causing any problems.
232
 *
233
 * @package core
234
 * @category completion
235
 * @copyright 2008 Sam Marshall
236
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
237
 */
238
class completion_info {
239
 
240
    /* @var stdClass Course object passed during construction */
241
    private $course;
242
 
243
    /* @var int Course id */
244
    public $course_id;
245
 
246
    /* @var array Completion criteria {@link completion_info::get_criteria()}  */
247
    private $criteria;
248
 
249
    /**
250
     * Return array of aggregation methods
251
     * @return array
252
     */
253
    public static function get_aggregation_methods() {
254
        return array(
255
            COMPLETION_AGGREGATION_ALL => get_string('all'),
256
            COMPLETION_AGGREGATION_ANY => get_string('any', 'completion'),
257
        );
258
    }
259
 
260
    /**
261
     * Constructs with course details.
262
     *
263
     * When instantiating a new completion info object you must provide a course
264
     * object with at least id, and enablecompletion properties. Property
265
     * cacherev is needed if you check completion of the current user since
266
     * it is used for cache validation.
267
     *
268
     * @param stdClass $course Moodle course object.
269
     */
270
    public function __construct($course) {
271
        $this->course = $course;
272
        $this->course_id = $course->id;
273
    }
274
 
275
    /**
276
     * Determines whether completion is enabled across entire site.
277
     *
278
     * @return bool COMPLETION_ENABLED (true) if completion is enabled for the site,
279
     *     COMPLETION_DISABLED (false) if it's complete
280
     */
281
    public static function is_enabled_for_site() {
282
        global $CFG;
283
        return !empty($CFG->enablecompletion);
284
    }
285
 
286
    /**
287
     * Checks whether completion is enabled in a particular course and possibly
288
     * activity.
289
     *
290
     * @param stdClass|cm_info $cm Course-module object. If not specified, returns the course
291
     *   completion enable state.
292
     * @return mixed COMPLETION_ENABLED or COMPLETION_DISABLED (==0) in the case of
293
     *   site and course; COMPLETION_TRACKING_MANUAL, _AUTOMATIC or _NONE (==0)
294
     *   for a course-module.
295
     */
296
    public function is_enabled($cm = null) {
297
        global $CFG, $DB;
298
 
299
        // First check global completion
300
        if (!isset($CFG->enablecompletion) || $CFG->enablecompletion == COMPLETION_DISABLED) {
301
            return COMPLETION_DISABLED;
302
        }
303
 
304
        // Load data if we do not have enough
305
        if (!isset($this->course->enablecompletion)) {
306
            $this->course = get_course($this->course_id);
307
        }
308
 
309
        // Check course completion
310
        if ($this->course->enablecompletion == COMPLETION_DISABLED) {
311
            return COMPLETION_DISABLED;
312
        }
313
 
314
        // If there was no $cm and we got this far, then it's enabled
315
        if (!$cm) {
316
            return COMPLETION_ENABLED;
317
        }
318
 
319
        // Return course-module completion value
320
        return $cm->completion;
321
    }
322
 
323
    /**
324
     * Get a course completion for a user
325
     *
326
     * @param int $user_id User id
327
     * @param int $criteriatype Specific criteria type to return
328
     * @return bool|completion_criteria_completion returns false on fail
329
     */
330
    public function get_completion($user_id, $criteriatype) {
331
        $completions = $this->get_completions($user_id, $criteriatype);
332
 
333
        if (empty($completions)) {
334
            return false;
335
        } elseif (count($completions) > 1) {
336
            throw new \moodle_exception('multipleselfcompletioncriteria', 'completion');
337
        }
338
 
339
        return $completions[0];
340
    }
341
 
342
    /**
343
     * Get all course criteria's completion objects for a user
344
     *
345
     * @param int $user_id User id
346
     * @param int $criteriatype Specific criteria type to return (optional)
347
     * @return array
348
     */
349
    public function get_completions($user_id, $criteriatype = null) {
350
        $criteria = $this->get_criteria($criteriatype);
351
 
352
        $completions = array();
353
 
354
        foreach ($criteria as $criterion) {
355
            $params = array(
356
                'course'        => $this->course_id,
357
                'userid'        => $user_id,
358
                'criteriaid'    => $criterion->id
359
            );
360
 
361
            $completion = new completion_criteria_completion($params);
362
            $completion->attach_criteria($criterion);
363
 
364
            $completions[] = $completion;
365
        }
366
 
367
        return $completions;
368
    }
369
 
370
    /**
371
     * Get completion object for a user and a criteria
372
     *
373
     * @param int $user_id User id
374
     * @param completion_criteria $criteria Criteria object
375
     * @return completion_criteria_completion
376
     */
377
    public function get_user_completion($user_id, $criteria) {
378
        $params = array(
379
            'course'        => $this->course_id,
380
            'userid'        => $user_id,
381
            'criteriaid'    => $criteria->id,
382
        );
383
 
384
        $completion = new completion_criteria_completion($params);
385
        return $completion;
386
    }
387
 
388
    /**
389
     * Check if course has completion criteria set
390
     *
391
     * @return bool Returns true if there are criteria
392
     */
393
    public function has_criteria() {
394
        $criteria = $this->get_criteria();
395
 
396
        return (bool) count($criteria);
397
    }
398
 
399
    /**
400
     * Get course completion criteria
401
     *
402
     * @param int $criteriatype Specific criteria type to return (optional)
403
     */
404
    public function get_criteria($criteriatype = null) {
405
 
406
        // Fill cache if empty
407
        if (!is_array($this->criteria)) {
408
            global $DB;
409
 
410
            $params = array(
411
                'course'    => $this->course->id
412
            );
413
 
414
            // Load criteria from database
415
            $records = (array)$DB->get_records('course_completion_criteria', $params);
416
 
417
            // Order records so activities are in the same order as they appear on the course view page.
418
            if ($records) {
419
                $activitiesorder = array_keys(get_fast_modinfo($this->course)->get_cms());
420
                usort($records, function ($a, $b) use ($activitiesorder) {
421
                    $aidx = ($a->criteriatype == COMPLETION_CRITERIA_TYPE_ACTIVITY) ?
422
                        array_search($a->moduleinstance, $activitiesorder) : false;
423
                    $bidx = ($b->criteriatype == COMPLETION_CRITERIA_TYPE_ACTIVITY) ?
424
                        array_search($b->moduleinstance, $activitiesorder) : false;
425
                    if ($aidx === false || $bidx === false || $aidx == $bidx) {
426
                        return 0;
427
                    }
428
                    return ($aidx < $bidx) ? -1 : 1;
429
                });
430
            }
431
 
432
            // Build array of criteria objects
433
            $this->criteria = array();
434
            foreach ($records as $record) {
435
                $this->criteria[$record->id] = completion_criteria::factory((array)$record);
436
            }
437
        }
438
 
439
        // If after all criteria
440
        if ($criteriatype === null) {
441
            return $this->criteria;
442
        }
443
 
444
        // If we are only after a specific criteria type
445
        $criteria = array();
446
        foreach ($this->criteria as $criterion) {
447
 
448
            if ($criterion->criteriatype != $criteriatype) {
449
                continue;
450
            }
451
 
452
            $criteria[$criterion->id] = $criterion;
453
        }
454
 
455
        return $criteria;
456
    }
457
 
458
    /**
459
     * Get aggregation method
460
     *
461
     * @param int $criteriatype If none supplied, get overall aggregation method (optional)
462
     * @return int One of COMPLETION_AGGREGATION_ALL or COMPLETION_AGGREGATION_ANY
463
     */
464
    public function get_aggregation_method($criteriatype = null) {
465
        $params = array(
466
            'course'        => $this->course_id,
467
            'criteriatype'  => $criteriatype
468
        );
469
 
470
        $aggregation = new completion_aggregation($params);
471
 
472
        if (!$aggregation->id) {
473
            $aggregation->method = COMPLETION_AGGREGATION_ALL;
474
        }
475
 
476
        return $aggregation->method;
477
    }
478
 
479
    /**
480
     * Clear old course completion criteria
481
     */
482
    public function clear_criteria() {
483
        global $DB;
484
 
485
        // Remove completion criteria records for the course itself, and any records that refer to the course.
486
        $select = 'course = :course OR (criteriatype = :type AND courseinstance = :courseinstance)';
487
        $params = [
488
            'course' => $this->course_id,
489
            'type' => COMPLETION_CRITERIA_TYPE_COURSE,
490
            'courseinstance' => $this->course_id,
491
        ];
492
 
493
        $DB->delete_records_select('course_completion_criteria', $select, $params);
494
        $DB->delete_records('course_completion_aggr_methd', array('course' => $this->course_id));
495
 
496
        $this->delete_course_completion_data();
497
    }
498
 
499
    /**
500
     * Has the supplied user completed this course
501
     *
502
     * @param int $user_id User's id
503
     * @return boolean
504
     */
505
    public function is_course_complete($user_id) {
506
        $params = array(
507
            'userid'    => $user_id,
508
            'course'  => $this->course_id
509
        );
510
 
511
        $ccompletion = new completion_completion($params);
512
        return $ccompletion->is_complete();
513
    }
514
 
515
    /**
516
     * Check whether the supplied user can override the activity completion statuses within the current course.
517
     *
518
     * @param stdClass $user The user object.
519
     * @return bool True if the user can override, false otherwise.
520
     */
521
    public function user_can_override_completion($user) {
522
        return has_capability('moodle/course:overridecompletion', context_course::instance($this->course_id), $user);
523
    }
524
 
525
    /**
526
     * Updates (if necessary) the completion state of activity $cm for the given
527
     * user.
528
     *
529
     * For manual completion, this function is called when completion is toggled
530
     * with $possibleresult set to the target state.
531
     *
532
     * For automatic completion, this function should be called every time a module
533
     * does something which might influence a user's completion state. For example,
534
     * if a forum provides options for marking itself 'completed' once a user makes
535
     * N posts, this function should be called every time a user makes a new post.
536
     * [After the post has been saved to the database]. When calling, you do not
537
     * need to pass in the new completion state. Instead this function carries out completion
538
     * calculation by checking grades and viewed state itself, and calling the involved module
539
     * via mod_{modulename}\\completion\\custom_completion::get_overall_completion_state() to
540
     * check module-specific conditions.
541
     *
542
     * @param stdClass|cm_info $cm Course-module
543
     * @param int $possibleresult Expected completion result. If the event that
544
     *   has just occurred (e.g. add post) can only result in making the activity
545
     *   complete when it wasn't before, use COMPLETION_COMPLETE. If the event that
546
     *   has just occurred (e.g. delete post) can only result in making the activity
547
     *   not complete when it was previously complete, use COMPLETION_INCOMPLETE.
548
     *   Otherwise use COMPLETION_UNKNOWN. Setting this value to something other than
549
     *   COMPLETION_UNKNOWN significantly improves performance because it will abandon
550
     *   processing early if the user's completion state already matches the expected
551
     *   result. For manual events, COMPLETION_COMPLETE or COMPLETION_INCOMPLETE
552
     *   must be used; these directly set the specified state.
553
     * @param int $userid User ID to be updated. Default 0 = current user
554
     * @param bool $override Whether manually overriding the existing completion state.
555
     * @param bool $isbulkupdate If bulk grade update is happening.
556
     * @return void
557
     * @throws moodle_exception if trying to override without permission.
558
     */
559
    public function update_state($cm, $possibleresult=COMPLETION_UNKNOWN, $userid=0,
560
            $override = false, $isbulkupdate = false) {
561
        global $USER;
562
 
563
        // Do nothing if completion is not enabled for that activity
564
        if (!$this->is_enabled($cm)) {
565
            return;
566
        }
567
 
568
        // If we're processing an override and the current user isn't allowed to do so, then throw an exception.
569
        if ($override) {
570
            if (!$this->user_can_override_completion($USER)) {
571
                throw new required_capability_exception(context_course::instance($this->course_id),
572
                                                        'moodle/course:overridecompletion', 'nopermission', '');
573
            }
574
        }
575
 
576
        // Default to current user if one is not provided.
577
        if ($userid == 0) {
578
            $userid = $USER->id;
579
        }
580
 
581
        // Delete the cm's cached completion data for this user if automatic completion is enabled.
582
        // This ensures any changes to the status of individual completion conditions in the activity will be fetched.
583
        if ($cm->completion == COMPLETION_TRACKING_AUTOMATIC) {
584
            $completioncache = cache::make('core', 'completion');
585
            $completionkey = $userid . '_' . $this->course->id;
586
            $completiondata = $completioncache->get($completionkey);
587
 
588
            if ($completiondata !== false) {
589
                unset($completiondata[$cm->id]);
590
                $completioncache->set($completionkey, $completiondata);
591
            }
592
        }
593
 
594
        // Get current value of completion state and do nothing if it's same as
595
        // the possible result of this change. If the change is to COMPLETE and the
596
        // current value is one of the COMPLETE_xx subtypes, ignore that as well
597
        $current = $this->get_data($cm, false, $userid);
598
        if ($possibleresult == $current->completionstate ||
599
            ($possibleresult == COMPLETION_COMPLETE &&
600
                ($current->completionstate == COMPLETION_COMPLETE_PASS ||
601
                $current->completionstate == COMPLETION_COMPLETE_FAIL))) {
602
            return;
603
        }
604
 
605
        // For auto tracking, if the status is overridden to 'COMPLETION_COMPLETE', then disallow further changes,
606
        // unless processing another override.
607
        // Basically, we want those activities which have been overridden to COMPLETE to hold state, and those which have been
608
        // overridden to INCOMPLETE to still be processed by normal completion triggers.
609
        if ($cm->completion == COMPLETION_TRACKING_AUTOMATIC && !is_null($current->overrideby)
610
            && $current->completionstate == COMPLETION_COMPLETE && !$override) {
611
            return;
612
        }
613
 
614
        // For manual tracking, or if overriding the completion state, we set the state directly.
615
        if ($cm->completion == COMPLETION_TRACKING_MANUAL || $override) {
616
            switch($possibleresult) {
617
                case COMPLETION_COMPLETE:
618
                case COMPLETION_INCOMPLETE:
619
                    $newstate = $possibleresult;
620
                    break;
621
                default:
622
                    $this->internal_systemerror("Unexpected manual completion state for {$cm->id}: $possibleresult");
623
            }
624
 
625
        } else {
626
            $newstate = $this->internal_get_state($cm, $userid, $current);
627
        }
628
 
629
        // If the overall completion state has changed, update it in the cache.
630
        if ($newstate != $current->completionstate) {
631
            $current->completionstate = $newstate;
632
            $current->timemodified    = time();
633
            $current->overrideby      = $override ? $USER->id : null;
634
            $this->internal_set_data($cm, $current, $isbulkupdate);
1441 ariadna 635
 
636
            // Dispatch the hook for course content update.
637
            // The activity completion alters the course state cache for this particular user.
638
            $course = get_course($cm->course);
639
            if ($course) {
640
                $modinfo = get_fast_modinfo($course);
641
                $cminfo = $modinfo->get_cm($cm->id);
642
                $hook = new \core_completion\hook\after_cm_completion_updated(
643
                    cm: $cminfo,
644
                    data: $current,
645
                );
646
                \core\di::get(\core\hook\manager::class)->dispatch($hook);
647
            }
1 efrain 648
        }
649
    }
650
 
651
    /**
652
     * Calculates the completion state for an activity and user.
653
     *
654
     * Internal function. Not private, so we can unit-test it.
655
     *
656
     * @param stdClass|cm_info $cm Activity
657
     * @param int $userid ID of user
658
     * @param stdClass $current Previous completion information from database
659
     * @return mixed
660
     */
661
    public function internal_get_state($cm, $userid, $current) {
662
        global $USER, $DB;
663
 
664
        // Get user ID
665
        if (!$userid) {
666
            $userid = $USER->id;
667
        }
668
 
669
        $newstate = COMPLETION_COMPLETE;
670
        if ($cm instanceof stdClass) {
671
            // Modname hopefully is provided in $cm but just in case it isn't, let's grab it.
672
            if (!isset($cm->modname)) {
673
                $cm->modname = $DB->get_field('modules', 'name', array('id' => $cm->module));
674
            }
675
            // Some functions call this method and pass $cm as an object with ID only. Make sure course is set as well.
676
            if (!isset($cm->course)) {
677
                $cm->course = $this->course_id;
678
            }
679
        }
680
        // Make sure we're using a cm_info object.
681
        $cminfo = cm_info::create($cm, $userid);
682
        $completionstate = $this->get_core_completion_state($cminfo, $userid);
683
 
684
        if (plugin_supports('mod', $cminfo->modname, FEATURE_COMPLETION_HAS_RULES)) {
685
            $cmcompletionclass = activity_custom_completion::get_cm_completion_class($cminfo->modname);
686
            if ($cmcompletionclass) {
687
                /** @var activity_custom_completion $cmcompletion */
688
                $cmcompletion = new $cmcompletionclass($cminfo, $userid, $completionstate);
689
                $customstate = $cmcompletion->get_overall_completion_state();
690
                if ($customstate == COMPLETION_INCOMPLETE) {
691
                    return $customstate;
692
                }
693
                $completionstate[] = $customstate;
694
            }
695
        }
696
 
697
        if ($completionstate) {
698
            // We have allowed the plugins to do it's thing and run their own checks.
699
            // We have now reached a state where we need to AND all the calculated results.
700
            // Preference for COMPLETION_COMPLETE_PASS over COMPLETION_COMPLETE for proper indication in reports.
701
            $newstate = array_reduce($completionstate, function($carry, $value) {
702
                if (in_array(COMPLETION_INCOMPLETE, [$carry, $value])) {
703
                    return COMPLETION_INCOMPLETE;
704
                } else if (in_array(COMPLETION_COMPLETE_FAIL, [$carry, $value])) {
705
                    return COMPLETION_COMPLETE_FAIL;
706
                } else {
707
                    return in_array(COMPLETION_COMPLETE_PASS, [$carry, $value]) ? COMPLETION_COMPLETE_PASS : $value;
708
                }
709
 
710
            }, COMPLETION_COMPLETE);
711
        }
712
 
713
        return $newstate;
714
 
715
    }
716
 
717
    /**
718
     * Fetches the completion state for an activity completion's require grade completion requirement.
719
     *
720
     * @param cm_info $cm The course module information.
721
     * @param int $userid The user ID.
722
     * @return int The completion state.
723
     */
724
    public function get_grade_completion(cm_info $cm, int $userid): int {
725
        global $CFG;
726
 
727
        require_once($CFG->libdir . '/gradelib.php');
728
        $item = grade_item::fetch([
729
            'courseid' => $cm->course,
730
            'itemtype' => 'mod',
731
            'itemmodule' => $cm->modname,
732
            'iteminstance' => $cm->instance,
733
            'itemnumber' => $cm->completiongradeitemnumber
734
        ]);
735
        if ($item) {
736
            // Fetch 'grades' (will be one or none).
737
            $grades = grade_grade::fetch_users_grades($item, [$userid], false);
738
            if (empty($grades)) {
739
                // No grade for user.
740
                return COMPLETION_INCOMPLETE;
741
            }
742
            if (count($grades) > 1) {
743
                $this->internal_systemerror("Unexpected result: multiple grades for
744
                        item '{$item->id}', user '{$userid}'");
745
            }
746
            $returnpassfail = !empty($cm->completionpassgrade);
747
            return self::internal_get_grade_state($item, reset($grades), $returnpassfail);
748
        }
749
 
750
        return COMPLETION_INCOMPLETE;
751
    }
752
 
753
    /**
754
     * Marks a module as viewed.
755
     *
756
     * Should be called whenever a module is 'viewed' (it is up to the module how to
757
     * determine that). Has no effect if viewing is not set as a completion condition.
758
     *
759
     * Note that this function must be called before you print the page header because
760
     * it is possible that the navigation block may depend on it. If you call it after
761
     * printing the header, it shows a developer debug warning.
762
     *
763
     * @param stdClass|cm_info $cm Activity
764
     * @param int $userid User ID or 0 (default) for current user
765
     * @return void
766
     */
767
    public function set_module_viewed($cm, $userid=0) {
768
        global $PAGE;
769
        if ($PAGE->headerprinted) {
770
            debugging('set_module_viewed must be called before header is printed',
771
                    DEBUG_DEVELOPER);
772
        }
773
 
774
        // Don't do anything if view condition is not turned on
775
        if ($cm->completionview == COMPLETION_VIEW_NOT_REQUIRED || !$this->is_enabled($cm)) {
776
            return;
777
        }
778
 
779
        // Get current completion state
780
        $data = $this->get_data($cm, false, $userid);
781
 
782
        // If we already viewed it, don't do anything unless the completion status is overridden.
783
        // If the completion status is overridden, then we need to allow this 'view' to trigger automatic completion again.
784
        if ($data->viewed == COMPLETION_VIEWED && empty($data->overrideby)) {
785
            return;
786
        }
787
 
788
        // OK, change state, save it, and update completion
789
        $data->viewed = COMPLETION_VIEWED;
790
        $this->internal_set_data($cm, $data);
791
        $this->update_state($cm, COMPLETION_COMPLETE, $userid);
792
    }
793
 
794
    /**
795
     * Determines how much completion data exists for an activity. This is used when
796
     * deciding whether completion information should be 'locked' in the module
797
     * editing form.
798
     *
799
     * @param cm_info $cm Activity
800
     * @return int The number of users who have completion data stored for this
801
     *   activity, 0 if none
802
     */
803
    public function count_user_data($cm) {
804
        global $DB;
805
 
806
        return $DB->get_field_sql("
807
    SELECT
808
        COUNT(1)
809
    FROM
810
        {course_modules_completion}
811
    WHERE
812
        coursemoduleid=? AND completionstate<>0", array($cm->id));
813
    }
814
 
815
    /**
816
     * Determines how much course completion data exists for a course. This is used when
817
     * deciding whether completion information should be 'locked' in the completion
818
     * settings form and activity completion settings.
819
     *
820
     * @param int $user_id Optionally only get course completion data for a single user
821
     * @return int The number of users who have completion data stored for this
822
     *     course, 0 if none
823
     */
824
    public function count_course_user_data($user_id = null) {
825
        global $DB;
826
 
827
        $sql = '
828
    SELECT
829
        COUNT(1)
830
    FROM
831
        {course_completion_crit_compl}
832
    WHERE
833
        course = ?
834
        ';
835
 
836
        $params = array($this->course_id);
837
 
838
        // Limit data to a single user if an ID is supplied
839
        if ($user_id) {
840
            $sql .= ' AND userid = ?';
841
            $params[] = $user_id;
842
        }
843
 
844
        return $DB->get_field_sql($sql, $params);
845
    }
846
 
847
    /**
848
     * Check if this course's completion criteria should be locked
849
     *
850
     * @return boolean
851
     */
852
    public function is_course_locked() {
853
        return (bool) $this->count_course_user_data();
854
    }
855
 
856
    /**
857
     * Deletes all course completion completion data.
858
     *
859
     * Intended to be used when unlocking completion criteria settings.
860
     */
861
    public function delete_course_completion_data() {
862
        global $DB;
863
 
864
        $DB->delete_records('course_completions', array('course' => $this->course_id));
865
        $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id));
866
 
867
        // Difficult to find affected users, just purge all completion cache.
868
        cache::make('core', 'completion')->purge();
869
        cache::make('core', 'coursecompletion')->purge();
870
    }
871
 
872
    /**
873
     * Deletes all activity and course completion data for an entire course
874
     * (the below delete_all_state function does this for a single activity).
875
     *
876
     * Used by course reset page.
877
     */
878
    public function delete_all_completion_data() {
879
        global $DB;
880
 
881
        // Delete from database.
882
        $DB->delete_records_select('course_modules_completion',
883
                'coursemoduleid IN (SELECT id FROM {course_modules} WHERE course=?)',
884
                array($this->course_id));
885
        $DB->delete_records_select('course_modules_viewed',
886
            'coursemoduleid IN (SELECT id FROM {course_modules} WHERE course=?)',
887
            [$this->course_id]);
888
        // Wipe course completion data too.
889
        $this->delete_course_completion_data();
890
    }
891
 
892
    /**
893
     * Deletes completion state related to an activity for all users.
894
     *
895
     * Intended for use only when the activity itself is deleted.
896
     *
897
     * @param stdClass|cm_info $cm Activity
898
     */
899
    public function delete_all_state($cm) {
900
        global $DB;
901
 
902
        // Delete from database
903
        $DB->delete_records('course_modules_completion', array('coursemoduleid'=>$cm->id));
904
 
905
        // Check if there is an associated course completion criteria
906
        $criteria = $this->get_criteria(COMPLETION_CRITERIA_TYPE_ACTIVITY);
907
        $acriteria = false;
908
        foreach ($criteria as $criterion) {
909
            if ($criterion->moduleinstance == $cm->id) {
910
                $acriteria = $criterion;
911
                break;
912
            }
913
        }
914
 
915
        if ($acriteria) {
916
            // Delete all criteria completions relating to this activity
917
            $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id, 'criteriaid' => $acriteria->id));
918
            $DB->delete_records('course_completions', array('course' => $this->course_id));
919
        }
920
 
921
        // Difficult to find affected users, just purge all completion cache.
922
        cache::make('core', 'completion')->purge();
923
        cache::make('core', 'coursecompletion')->purge();
924
    }
925
 
926
    /**
927
     * Recalculates completion state related to an activity for all users.
928
     *
929
     * Intended for use if completion conditions change. (This should be avoided
930
     * as it may cause some things to become incomplete when they were previously
931
     * complete, with the effect - for example - of hiding a later activity that
932
     * was previously available.)
933
     *
934
     * Resetting state of manual tickbox has same result as deleting state for
935
     * it.
936
     *
937
     * @param stdClass|cm_info $cm Activity
938
     */
939
    public function reset_all_state($cm) {
940
        global $DB;
941
 
942
        if ($cm->completion == COMPLETION_TRACKING_MANUAL) {
943
            $this->delete_all_state($cm);
944
            return;
945
        }
946
        // Get current list of users with completion state
947
        $rs = $DB->get_recordset('course_modules_completion', array('coursemoduleid'=>$cm->id), '', 'userid');
948
        $keepusers = array();
949
        foreach ($rs as $rec) {
950
            $keepusers[] = $rec->userid;
951
        }
952
        $rs->close();
953
 
954
        // Delete all existing state.
955
        $this->delete_all_state($cm);
956
 
957
        // Merge this with list of planned users (according to roles)
958
        $trackedusers = $this->get_tracked_users();
959
        foreach ($trackedusers as $trackeduser) {
960
            $keepusers[] = $trackeduser->id;
961
        }
962
        $keepusers = array_unique($keepusers);
963
 
964
        // Recalculate state for each kept user
965
        foreach ($keepusers as $keepuser) {
966
            $this->update_state($cm, COMPLETION_UNKNOWN, $keepuser);
967
        }
968
    }
969
 
970
    /**
971
     * Obtains completion data for a particular activity and user (from the
972
     * completion cache if available, or by SQL query)
973
     *
974
     * @param stdClass|cm_info $cm Activity; only required field is ->id
975
     * @param bool $wholecourse If true (default false) then, when necessary to
976
     *   fill the cache, retrieves information from the entire course not just for
977
     *   this one activity
978
     * @param int $userid User ID or 0 (default) for current user
979
     * @param mixed $unused This parameter has been deprecated since 4.0 and should not be used anymore.
980
     * @return object Completion data. Record from course_modules_completion plus other completion statuses such as
981
     *                  - Completion status for 'must-receive-grade' completion rule.
982
     *                  - Custom completion statuses defined by the activity module plugin.
983
     */
984
    public function get_data($cm, $wholecourse = false, $userid = 0, $unused = null) {
985
        global $USER, $DB;
986
 
987
        if ($unused !== null) {
988
            debugging('Deprecated argument passed to ' . __FUNCTION__, DEBUG_DEVELOPER);
989
        }
990
 
991
        $completioncache = cache::make('core', 'completion');
992
 
993
        // Get user ID
994
        if (!$userid) {
995
            $userid = $USER->id;
996
        }
997
 
998
        // Some call completion_info::get_data and pass $cm as an object with ID only. Make sure course is set as well.
999
        if ($cm instanceof stdClass && !isset($cm->course)) {
1000
            $cm->course = $this->course_id;
1001
        }
1002
        // Make sure we're working on a cm_info object.
1003
        $cminfo = cm_info::create($cm, $userid);
1004
 
1005
        // Create an anonymous function to remove the 'other_cm_completion_data_fetched' key.
1006
        $returnfilteredvalue = function(array $value): stdClass {
1007
            return (object) array_filter($value, function(string $key): bool {
1008
                return $key !== 'other_cm_completion_data_fetched';
1009
            }, ARRAY_FILTER_USE_KEY);
1010
        };
1011
 
1012
        // See if requested data is present in cache (use cache for current user only).
1013
        $usecache = $userid == $USER->id;
1014
        $cacheddata = array();
1015
        if ($usecache) {
1016
            $key = $userid . '_' . $this->course->id;
1017
            if (!isset($this->course->cacherev)) {
1018
                $this->course = get_course($this->course_id);
1019
            }
1020
            if ($cacheddata = ($completioncache->get($key) ?: [])) {
1021
                if ($cacheddata['cacherev'] != $this->course->cacherev) {
1022
                    // Course structure has been changed since the last caching, forget the cache.
1023
                    $cacheddata = array();
1024
                } else if (isset($cacheddata[$cminfo->id])) {
1025
                    $data = (array) $cacheddata[$cminfo->id];
1026
                    if (empty($data['other_cm_completion_data_fetched'])) {
1027
                        $data += $this->get_other_cm_completion_data($cminfo, $userid);
1028
                        $data['other_cm_completion_data_fetched'] = true;
1029
 
1030
                        // Put in cache.
1031
                        $cacheddata[$cminfo->id] = $data;
1032
                        $completioncache->set($key, $cacheddata);
1033
                    }
1034
 
1035
                    return $returnfilteredvalue($cacheddata[$cminfo->id]);
1036
                }
1037
            }
1038
        }
1039
 
1040
        // Default data to return when no completion data is found.
1041
        $defaultdata = [
1042
            'id' => 0,
1043
            'coursemoduleid' => $cminfo->id,
1044
            'userid' => $userid,
1045
            'completionstate' => 0,
1046
            'viewed' => 0,
1047
            'overrideby' => null,
1048
            'timemodified' => 0,
1049
        ];
1050
 
1051
        // If cached completion data is not found, fetch via SQL.
1052
        // Fetch completion data for all of the activities in the course ONLY if we're caching the fetched completion data.
1053
        // If we're not caching the completion data, then just fetch the completion data for the user in this course module.
1054
        if ($usecache && $wholecourse) {
1055
            // Get whole course data for cache.
1056
            $alldatabycmc = $DB->get_records_sql("SELECT cm.id AS cmid, cmc.*,
1057
                                                         CASE WHEN cmv.id IS NULL THEN 0 ELSE 1 END AS viewed
1058
                                                    FROM {course_modules} cm
1059
                                               LEFT JOIN {course_modules_completion} cmc
1060
                                                         ON cmc.coursemoduleid = cm.id  AND cmc.userid = ?
1061
                                               LEFT JOIN {course_modules_viewed} cmv
1062
                                                         ON cmv.coursemoduleid = cm.id  AND cmv.userid = ?
1063
                                              INNER JOIN {modules} m ON m.id = cm.module
1064
                                                   WHERE m.visible = 1 AND cm.course = ?",
1065
                [$userid, $userid, $this->course->id]);
1066
            $cminfos = get_fast_modinfo($cm->course, $userid)->get_cms();
1067
 
1068
            // Reindex by course module id.
1069
            foreach ($alldatabycmc as $data) {
1070
 
1071
                // Filter acitivites with no cm_info (missing plugins or other causes).
1072
                if (!isset($cminfos[$data->cmid])) {
1073
                    continue;
1074
                }
1075
 
1076
                if (empty($data->coursemoduleid)) {
1077
                    $cacheddata[$data->cmid] = $defaultdata;
1078
                    if ($data->viewed) {
1079
                        $cacheddata[$data->cmid]['viewed'] = $data->viewed;
1080
                    }
1081
                    $cacheddata[$data->cmid]['coursemoduleid'] = $data->cmid;
1082
                } else {
1083
                    unset($data->cmid);
1084
                    $cacheddata[$data->coursemoduleid] = (array) $data;
1085
                }
1086
            }
1087
 
1088
            if (!isset($cacheddata[$cminfo->id])) {
1089
                $errormessage = "Unexpected error: course-module {$cminfo->id} could not be found on course {$this->course->id}";
1090
                $this->internal_systemerror($errormessage);
1091
            }
1092
 
1093
            $data = $cacheddata[$cminfo->id];
1094
        } else {
1095
            // Get single record
1096
            $data = $this->get_completion_data($cminfo->id, $userid, $defaultdata);
1097
            // Put in cache.
1098
            $cacheddata[$cminfo->id] = $data;
1099
        }
1100
 
1101
        // Fill the other completion data for this user in this module instance.
1102
        $data += $this->get_other_cm_completion_data($cminfo, $userid);
1103
        $data['other_cm_completion_data_fetched'] = true;
1104
 
1105
        // Put in cache
1106
        $cacheddata[$cminfo->id] = $data;
1107
 
1108
        if ($usecache) {
1109
            $cacheddata['cacherev'] = $this->course->cacherev;
1110
            $completioncache->set($key, $cacheddata);
1111
        }
1112
 
1113
        return $returnfilteredvalue($cacheddata[$cminfo->id]);
1114
    }
1115
 
1116
    /**
1117
     * Get the latest completion state for each criteria used in the module
1118
     *
1119
     * @param cm_info $cm The corresponding module's information
1120
     * @param int $userid The id for the user we are calculating core completion state
1121
     * @return array $data The individualised core completion state used in the module.
1122
     *                      Consists of the following keys completiongrade, passgrade, viewed
1123
     */
1124
    public function get_core_completion_state(cm_info $cm, int $userid): array {
1125
        global $DB;
1126
        $data = [];
1127
        // Include in the completion info the grade completion, if necessary.
1128
        if (!is_null($cm->completiongradeitemnumber)) {
1129
            $newstate = $this->get_grade_completion($cm, $userid);
1130
            $data['completiongrade'] = $newstate;
1131
 
1132
            if ($cm->completionpassgrade) {
1133
                // If we are asking to use pass grade completion but haven't set it properly,
1134
                // then default to COMPLETION_COMPLETE_PASS.
1135
                if ($newstate == COMPLETION_COMPLETE) {
1136
                    $newstate = COMPLETION_COMPLETE_PASS;
1137
                }
1138
 
1139
                // No need to show failing status for the completiongrade condition when passing grade condition is set.
1140
                if (in_array($newstate, [COMPLETION_COMPLETE_FAIL, COMPLETION_COMPLETE_FAIL_HIDDEN])) {
1141
                    $data['completiongrade'] = COMPLETION_COMPLETE;
1142
 
1143
                    // If the grade received by the user is a failing grade for a hidden grade item,
1144
                    // the 'Require passing grade' criterion is considered incomplete.
1145
                    if ($newstate == COMPLETION_COMPLETE_FAIL_HIDDEN) {
1146
                        $newstate = COMPLETION_INCOMPLETE;
1147
                    }
1148
                }
1149
                $data['passgrade'] = $newstate;
1150
            }
1151
        }
1152
 
1153
        // If view is required, try and fetch from the db. In some cases, cache can be invalid.
1154
        if ($cm->completionview == COMPLETION_VIEW_REQUIRED) {
1155
            $data['viewed'] = COMPLETION_INCOMPLETE;
1156
            $record = $DB->record_exists('course_modules_viewed', ['coursemoduleid' => $cm->id, 'userid' => $userid]);
1157
            $data['viewed'] = $record ? COMPLETION_COMPLETE : COMPLETION_INCOMPLETE;
1158
        }
1159
 
1160
        return $data;
1161
    }
1162
 
1163
    /**
1164
     * Adds the user's custom completion data on the given course module.
1165
     *
1166
     * @param cm_info $cm The course module information.
1167
     * @param int $userid The user ID.
1168
     * @return array The additional completion data.
1169
     */
1170
    protected function get_other_cm_completion_data(cm_info $cm, int $userid): array {
1171
        $data = $this->get_core_completion_state($cm, $userid);
1172
 
1173
        // Custom activity module completion data.
1174
 
1175
        // Cast custom data to array before checking for custom completion rules.
1176
        // We call ->get_custom_data() instead of ->customdata here because there is the chance of recursive calling,
1177
        // and we cannot call a getter from a getter in PHP.
1178
        $customdata = (array) $cm->get_custom_data();
1179
        // Return early if the plugin does not define custom completion rules.
1180
        if (empty($customdata['customcompletionrules'])) {
1181
            return $data;
1182
        }
1183
 
1184
        // Return early if the activity modules doe not implement the activity_custom_completion class.
1185
        $cmcompletionclass = activity_custom_completion::get_cm_completion_class($cm->modname);
1186
        if (!$cmcompletionclass) {
1187
            return $data;
1188
        }
1189
 
1190
        /** @var activity_custom_completion $customcmcompletion */
1191
        $customcmcompletion = new $cmcompletionclass($cm, $userid, $data);
1192
        foreach ($customdata['customcompletionrules'] as $rule => $enabled) {
1193
            if (!$enabled) {
1194
                // Skip inactive completion rules.
1195
                continue;
1196
            }
1197
            // Get this custom completion rule's completion state.
1198
            $data['customcompletion'][$rule] = $customcmcompletion->get_state($rule);
1199
        }
1200
 
1201
        return $data;
1202
    }
1203
 
1204
    /**
1205
     * Updates completion data for a particular coursemodule and user (user is
1206
     * determined from $data).
1207
     *
1208
     * (Internal function. Not private, so we can unit-test it.)
1209
     *
1210
     * @param stdClass|cm_info $cm Activity
1211
     * @param stdClass $data Data about completion for that user
1212
     * @param bool $isbulkupdate If bulk grade update is happening.
1213
     */
1214
    public function internal_set_data($cm, $data, $isbulkupdate = false) {
1215
        global $USER, $DB, $CFG;
1216
        require_once($CFG->dirroot.'/completion/criteria/completion_criteria_activity.php');
1217
 
1218
        $transaction = $DB->start_delegated_transaction();
1219
        if (!$data->id) {
1220
            // Check there isn't really a row
1221
            $data->id = $DB->get_field('course_modules_completion', 'id',
1222
                    array('coursemoduleid'=>$data->coursemoduleid, 'userid'=>$data->userid));
1223
        }
1224
        if (!$data->id) {
1225
            // Didn't exist before, needs creating
1226
            $data->id = $DB->insert_record('course_modules_completion', $data);
1227
        } else {
1228
            // Has real (nonzero) id meaning that a database row exists, update
1229
            $DB->update_record('course_modules_completion', $data);
1230
        }
1231
        $dataview = new stdClass();
1232
        $dataview->coursemoduleid = $data->coursemoduleid;
1233
        $dataview->userid = $data->userid;
1234
        $dataview->id = $DB->get_field('course_modules_viewed', 'id',
1235
            ['coursemoduleid' => $dataview->coursemoduleid, 'userid' => $dataview->userid]);
1236
        if (!$data->viewed && $dataview->id) {
1237
            $DB->delete_records('course_modules_viewed', ['id' => $dataview->id]);
1238
        }
1239
 
1240
        if (!$dataview->id && $data->viewed) {
1241
            $dataview->timecreated = time();
1242
            $dataview->id = $DB->insert_record('course_modules_viewed', $dataview);
1243
        }
1244
        $transaction->allow_commit();
1245
 
1246
        $cmcontext = context_module::instance($data->coursemoduleid);
1247
 
1248
        $completioncache = cache::make('core', 'completion');
1249
        $cachekey = "{$data->userid}_{$cm->course}";
1250
        if ($data->userid == $USER->id) {
1251
            // Fetch other completion data to cache (e.g. require grade completion status, custom completion rule statues).
1252
            $cminfo = cm_info::create($cm, $data->userid); // Make sure we're working on a cm_info object.
1253
            $otherdata = $this->get_other_cm_completion_data($cminfo, $data->userid);
1254
            foreach ($otherdata as $key => $value) {
1255
                $data->$key = $value;
1256
            }
1257
 
1258
            // Update module completion in user's cache.
1259
            if (!($cachedata = $completioncache->get($cachekey))
1260
                    || $cachedata['cacherev'] != $this->course->cacherev) {
1261
                $cachedata = array('cacherev' => $this->course->cacherev);
1262
            }
1263
            $cachedata[$cm->id] = (array) $data;
1264
            $cachedata[$cm->id]['other_cm_completion_data_fetched'] = true;
1265
            $completioncache->set($cachekey, $cachedata);
1266
 
1267
            // reset modinfo for user (no need to call rebuild_course_cache())
1268
            get_fast_modinfo($cm->course, 0, true);
1269
        } else {
1270
            // Remove another user's completion cache for this course.
1271
            $completioncache->delete($cachekey);
1272
        }
1273
 
1274
        // For single user actions the code must reevaluate some completion state instantly, see MDL-32103.
1275
        if ($isbulkupdate) {
1276
            return;
1277
        } else {
1278
            $userdata = ['userid' => $data->userid, 'courseid' => $this->course_id];
1279
            $coursecompletionid = \core_completion\api::mark_course_completions_activity_criteria($userdata);
1280
            if ($coursecompletionid) {
1281
                aggregate_completions($coursecompletionid);
1282
            }
1283
        }
1284
 
1285
        // Trigger an event for course module completion changed.
1286
        $event = \core\event\course_module_completion_updated::create(array(
1287
            'objectid' => $data->id,
1288
            'context' => $cmcontext,
1289
            'relateduserid' => $data->userid,
1290
            'other' => array(
1291
                'relateduserid' => $data->userid,
1292
                'overrideby' => $data->overrideby,
1293
                'completionstate' => $data->completionstate
1294
            )
1295
        ));
1296
        $event->add_record_snapshot('course_modules_completion', $data);
1297
        $event->trigger();
1298
    }
1299
 
1300
     /**
1301
     * Return whether or not the course has activities with completion enabled.
1302
     *
1303
     * @return boolean true when there is at least one activity with completion enabled.
1304
     */
1305
    public function has_activities() {
1306
        $modinfo = get_fast_modinfo($this->course);
1307
        foreach ($modinfo->get_cms() as $cm) {
1308
            if ($cm->completion != COMPLETION_TRACKING_NONE) {
1309
                return true;
1310
            }
1311
        }
1312
        return false;
1313
    }
1314
 
1315
    /**
1316
     * Obtains a list of activities for which completion is enabled on the
1317
     * course. The list is ordered by the section order of those activities.
1318
     *
1319
     * @return cm_info[] Array from $cmid => $cm of all activities with completion enabled,
1320
     *   empty array if none
1321
     */
1322
    public function get_activities() {
1323
        $modinfo = get_fast_modinfo($this->course);
1324
        $result = array();
1325
        foreach ($modinfo->get_cms() as $cm) {
1326
            if ($cm->completion != COMPLETION_TRACKING_NONE && !$cm->deletioninprogress) {
1327
                $result[$cm->id] = $cm;
1328
            }
1329
        }
1330
        return $result;
1331
    }
1332
 
1333
    /**
1334
     * Checks to see if the userid supplied has a tracked role in
1335
     * this course
1336
     *
1337
     * @param int $userid User id
1338
     * @return bool
1339
     */
1340
    public function is_tracked_user($userid) {
1341
        return is_enrolled(context_course::instance($this->course->id), $userid, 'moodle/course:isincompletionreports', true);
1342
    }
1343
 
1344
    /**
1345
     * Returns the number of users whose progress is tracked in this course.
1346
     *
1347
     * Optionally supply a search's where clause, or a group id.
1348
     *
1349
     * @param string $where Where clause sql (use 'u.whatever' for user table fields)
1350
     * @param array $whereparams Where clause params
1351
     * @param int $groupid Group id
1352
     * @return int Number of tracked users
1353
     */
1354
    public function get_num_tracked_users($where = '', $whereparams = array(), $groupid = 0) {
1355
        global $DB;
1356
 
1357
        list($enrolledsql, $enrolledparams) = get_enrolled_sql(
1358
                context_course::instance($this->course->id), 'moodle/course:isincompletionreports', $groupid, true);
1359
        $sql  = 'SELECT COUNT(eu.id) FROM (' . $enrolledsql . ') eu JOIN {user} u ON u.id = eu.id';
1360
        if ($where) {
1361
            $sql .= " WHERE $where";
1362
        }
1363
 
1364
        $params = array_merge($enrolledparams, $whereparams);
1365
        return $DB->count_records_sql($sql, $params);
1366
    }
1367
 
1368
    /**
1369
     * Return array of users whose progress is tracked in this course.
1370
     *
1371
     * Optionally supply a search's where clause, group id, sorting, paging.
1372
     *
1373
     * @param string $where Where clause sql, referring to 'u.' fields (optional)
1374
     * @param array $whereparams Where clause params (optional)
1375
     * @param int $groupid Group ID to restrict to (optional)
1376
     * @param string $sort Order by clause (optional)
1377
     * @param int $limitfrom Result start (optional)
1378
     * @param int $limitnum Result max size (optional)
1379
     * @param context $extracontext If set, includes extra user information fields
1380
     *   as appropriate to display for current user in this context
1381
     * @return array Array of user objects with user fields (including all identity fields)
1382
     */
1383
    public function get_tracked_users($where = '', $whereparams = array(), $groupid = 0,
1441 ariadna 1384
             $sort = '', $limitfrom = '', $limitnum = '', ?context $extracontext = null) {
1 efrain 1385
 
1386
        global $DB;
1387
 
1388
        list($enrolledsql, $params) = get_enrolled_sql(
1389
                context_course::instance($this->course->id),
1390
                'moodle/course:isincompletionreports', $groupid, true);
1391
 
1392
        $userfieldsapi = \core_user\fields::for_identity($extracontext)->with_name()->excluding('id', 'idnumber');
1393
        $fieldssql = $userfieldsapi->get_sql('u', true);
1394
        $sql = 'SELECT u.id, u.idnumber ' . $fieldssql->selects;
1395
        $sql .= ' FROM (' . $enrolledsql . ') eu JOIN {user} u ON u.id = eu.id';
1396
 
1397
        if ($where) {
1398
            $sql .= " AND $where";
1399
            $params = array_merge($params, $whereparams);
1400
        }
1401
 
1402
        $sql .= $fieldssql->joins;
1403
        $params = array_merge($params, $fieldssql->params);
1404
 
1405
        if ($sort) {
1406
            $sql .= " ORDER BY $sort";
1407
        }
1408
 
1409
        return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1410
    }
1411
 
1412
    /**
1413
     * Obtains progress information across a course for all users on that course, or
1414
     * for all users in a specific group. Intended for use when displaying progress.
1415
     *
1416
     * This includes only users who, in course context, have one of the roles for
1417
     * which progress is tracked (the gradebookroles admin option) and are enrolled in course.
1418
     *
1419
     * Users are included (in the first array) even if they do not have
1420
     * completion progress for any course-module.
1421
     *
1422
     * @param bool $sortfirstname If true, sort by first name, otherwise sort by
1423
     *   last name
1424
     * @param string $where Where clause sql (optional)
1425
     * @param array $where_params Where clause params (optional)
1426
     * @param int $groupid Group ID or 0 (default)/false for all groups
1427
     * @param int $pagesize Number of users to actually return (optional)
1428
     * @param int $start User to start at if paging (optional)
1429
     * @param context $extracontext If set, includes extra user information fields
1430
     *   as appropriate to display for current user in this context
1431
     * @return array with ->total and ->start (same as $start) and ->users;
1432
     *   an array of user objects (like mdl_user id, firstname, lastname)
1433
     *   containing an additional ->progress array of coursemoduleid => completionstate
1434
     */
1435
    public function get_progress_all($where = '', $where_params = array(), $groupid = 0,
1441 ariadna 1436
            $sort = '', $pagesize = '', $start = '', ?context $extracontext = null) {
1 efrain 1437
        global $CFG, $DB;
1438
 
1439
        // Get list of applicable users
1440
        $users = $this->get_tracked_users($where, $where_params, $groupid, $sort,
1441
                $start, $pagesize, $extracontext);
1442
 
1443
        // Get progress information for these users in groups of 1, 000 (if needed)
1444
        // to avoid making the SQL IN too long
1445
        $results = array();
1446
        $userids = array();
1447
        foreach ($users as $user) {
1448
            $userids[] = $user->id;
1449
            $results[$user->id] = $user;
1450
            $results[$user->id]->progress = array();
1451
        }
1452
 
1453
        for($i=0; $i<count($userids); $i+=1000) {
1454
            $blocksize = count($userids)-$i < 1000 ? count($userids)-$i : 1000;
1455
 
1456
            list($insql, $params) = $DB->get_in_or_equal(array_slice($userids, $i, $blocksize));
1457
            array_splice($params, 0, 0, array($this->course->id));
1458
            $rs = $DB->get_recordset_sql("
1459
                SELECT
1460
                    cmc.*
1461
                FROM
1462
                    {course_modules} cm
1463
                    INNER JOIN {course_modules_completion} cmc ON cm.id=cmc.coursemoduleid
1464
                WHERE
1465
                    cm.course=? AND cmc.userid $insql", $params);
1466
            foreach ($rs as $progress) {
1467
                $progress = (object)$progress;
1468
                $results[$progress->userid]->progress[$progress->coursemoduleid] = $progress;
1469
            }
1470
            $rs->close();
1471
        }
1472
 
1473
        return $results;
1474
    }
1475
 
1476
    /**
1477
     * Called by grade code to inform the completion system when a grade has
1478
     * been changed. If the changed grade is used to determine completion for
1479
     * the course-module, then the completion status will be updated.
1480
     *
1481
     * @param stdClass|cm_info $cm Course-module for item that owns grade
1482
     * @param grade_item $item Grade item
1483
     * @param stdClass|grade_grade $grade
1484
     * @param bool $deleted
1485
     * @param bool $isbulkupdate If bulk grade update is happening.
1486
     */
1487
    public function inform_grade_changed($cm, $item, $grade, $deleted, $isbulkupdate = false) {
1488
        // Bail out now if completion is not enabled for course-module, it is enabled
1489
        // but is set to manual, grade is not used to compute completion, or this
1490
        // is a different numbered grade
1491
        if (!$this->is_enabled($cm) ||
1492
            $cm->completion == COMPLETION_TRACKING_MANUAL ||
1493
            is_null($cm->completiongradeitemnumber) ||
1494
            $item->itemnumber != $cm->completiongradeitemnumber) {
1495
            return;
1496
        }
1497
 
1498
        // What is the expected result based on this grade?
1499
        if ($deleted) {
1500
            // Grade being deleted, so only change could be to make it incomplete
1501
            $possibleresult = COMPLETION_INCOMPLETE;
1502
        } else {
1503
            $possibleresult = self::internal_get_grade_state($item, $grade);
1504
        }
1505
 
1506
        // OK, let's update state based on this
1507
        $this->update_state($cm, $possibleresult, $grade->userid, false, $isbulkupdate);
1508
    }
1509
 
1510
    /**
1511
     * Calculates the completion state that would result from a graded item
1512
     * (where grade-based completion is turned on) based on the actual grade
1513
     * and settings.
1514
     *
1515
     * Internal function. Not private, so we can unit-test it.
1516
     *
1517
     * @param grade_item $item an instance of grade_item
1518
     * @param grade_grade $grade an instance of grade_grade
1519
     * @param bool $returnpassfail If course module has pass grade completion criteria
1520
     * @return int Completion state e.g. COMPLETION_INCOMPLETE
1521
     */
1522
    public static function internal_get_grade_state($item, $grade, bool $returnpassfail = false) {
1523
        // If no grade is supplied or the grade doesn't have an actual value, then
1524
        // this is not complete.
1525
        if (!$grade || (is_null($grade->finalgrade) && is_null($grade->rawgrade))) {
1526
            return COMPLETION_INCOMPLETE;
1527
        }
1528
 
1529
        // Conditions to show pass/fail:
1530
        // a) Completion criteria to achieve pass grade is enabled
1531
        // or
1532
        // a) Grade has pass mark (default is 0.00000 which is boolean true so be careful)
1533
        // b) Grade is visible (neither hidden nor hidden-until)
1534
        if ($item->gradepass && $item->gradepass > 0.000009 && ($returnpassfail || !$item->hidden)) {
1535
            // Use final grade if set otherwise raw grade
1536
            $score = !is_null($grade->finalgrade) ? $grade->finalgrade : $grade->rawgrade;
1537
 
1538
            // We are displaying and tracking pass/fail
1539
            if ($score >= $item->gradepass) {
1540
                return COMPLETION_COMPLETE_PASS;
1541
            } else if ($item->hidden) {
1542
                return COMPLETION_COMPLETE_FAIL_HIDDEN;
1543
            } else {
1544
                return COMPLETION_COMPLETE_FAIL;
1545
            }
1546
        } else {
1547
            // Not displaying pass/fail, so just if there is a grade
1548
            if (!is_null($grade->finalgrade) || !is_null($grade->rawgrade)) {
1549
                // Grade exists, so maybe complete now
1550
                return COMPLETION_COMPLETE;
1551
            } else {
1552
                // Grade does not exist, so maybe incomplete now
1553
                return COMPLETION_INCOMPLETE;
1554
            }
1555
        }
1556
    }
1557
 
1558
    /**
1559
     * Aggregate activity completion state
1560
     *
1561
     * @param   int     $type   Aggregation type (COMPLETION_* constant)
1562
     * @param   bool    $old    Old state
1563
     * @param   bool    $new    New state
1564
     * @return  bool
1565
     */
1566
    public static function aggregate_completion_states($type, $old, $new) {
1567
        if ($type == COMPLETION_AND) {
1568
            return $old && $new;
1569
        } else {
1570
            return $old || $new;
1571
        }
1572
    }
1573
 
1574
    /**
1575
     * This is to be used only for system errors (things that shouldn't happen)
1576
     * and not user-level errors.
1577
     *
1578
     * @param string $error Error string (will not be displayed to user unless debugging is enabled)
1579
     * @throws moodle_exception Exception with the error string as debug info
1580
     */
1581
    public function internal_systemerror($error) {
1582
        global $CFG;
1583
        throw new moodle_exception('err_system','completion',
1584
            $CFG->wwwroot.'/course/view.php?id='.$this->course->id,null,$error);
1585
    }
1586
 
1587
    /**
1588
     * Get completion data include viewed field.
1589
     *
1590
     * @param int $coursemoduleid The course module id.
1591
     * @param int $userid The User ID.
1592
     * @param array $defaultdata Default data completion.
1593
     * @return array Data completion retrieved.
1594
     */
1595
    public function get_completion_data(int $coursemoduleid, int $userid, array $defaultdata): array {
1596
        global $DB;
1597
 
1598
        // MySQL doesn't support FULL JOIN syntax, so we use UNION in the below SQL to help MySQL.
1599
        $sql = "SELECT cmc.*, cmv.coursemoduleid as cmvcoursemoduleid, cmv.userid as cmvuserid
1600
                  FROM {course_modules_completion} cmc
1601
             LEFT JOIN {course_modules_viewed} cmv ON cmc.coursemoduleid = cmv.coursemoduleid AND cmc.userid = cmv.userid
1602
                 WHERE cmc.coursemoduleid = :cmccoursemoduleid AND cmc.userid = :cmcuserid
1603
                UNION
1604
                SELECT cmc2.*, cmv2.coursemoduleid as cmvcoursemoduleid, cmv2.userid as cmvuserid
1605
                  FROM {course_modules_completion} cmc2
1606
            RIGHT JOIN {course_modules_viewed} cmv2
1607
                    ON cmc2.coursemoduleid = cmv2.coursemoduleid AND cmc2.userid = cmv2.userid
1608
                 WHERE cmv2.coursemoduleid = :cmvcoursemoduleid AND cmv2.userid = :cmvuserid";
1609
 
1610
        $data = $DB->get_record_sql($sql, ['cmccoursemoduleid' => $coursemoduleid, 'cmcuserid' => $userid,
1611
            'cmvcoursemoduleid' => $coursemoduleid, 'cmvuserid' => $userid]);
1612
 
1613
        if (!$data) {
1614
            $data = $defaultdata;
1615
        } else {
1616
            if (empty($data->coursemoduleid) && empty($data->userid)) {
1617
                $data->coursemoduleid = $data->cmvcoursemoduleid;
1618
                $data->userid = $data->cmvuserid;
1619
            }
11 efrain 1620
            // When reseting all state in the completion, we need to keep current view state.
1621
            // We cannot assume the activity has been viewed, so we should check if there is any course_modules_viewed already.
1622
            $data->viewed = is_null($data->cmvuserid) ? 0 : 1;
1623
 
1 efrain 1624
            unset($data->cmvcoursemoduleid);
1625
            unset($data->cmvuserid);
1626
        }
1627
 
1628
        return (array)$data;
1629
    }
1441 ariadna 1630
 
1631
    /**
1632
     * Return the number of modules completed by a user in one specific course.
1633
     *
1634
     * @param int $userid The User ID.
1635
     * @return int Total number of modules completed by a user
1636
     */
1637
    public function count_modules_completed(int $userid): int {
1638
        global $DB;
1639
 
1640
        $sql = "SELECT COUNT(1)
1641
                  FROM {course_modules} cm
1642
                  JOIN {course_modules_completion} cmc ON cm.id = cmc.coursemoduleid
1643
                 WHERE cm.course = :courseid
1644
                       AND cmc.userid = :userid
1645
                       AND (cmc.completionstate = " . COMPLETION_COMPLETE . "
1646
                        OR cmc.completionstate = " . COMPLETION_COMPLETE_PASS . ")";
1647
        $params = ['courseid' => $this->course_id, 'userid' => $userid];
1648
 
1649
        return $DB->count_records_sql($sql, $params);
1650
    }
1 efrain 1651
}
1652
 
1653
/**
1654
 * Aggregate criteria status's as per configured aggregation method.
1655
 *
1656
 * @param int $method COMPLETION_AGGREGATION_* constant.
1657
 * @param bool $data Criteria completion status.
1658
 * @param bool|null $state Aggregation state.
1659
 */
1660
function completion_cron_aggregate($method, $data, &$state) {
1661
    if ($method == COMPLETION_AGGREGATION_ALL) {
1662
        if ($data && $state !== false) {
1663
            $state = true;
1664
        } else {
1665
            $state = false;
1666
        }
1667
    } else if ($method == COMPLETION_AGGREGATION_ANY) {
1668
        if ($data) {
1669
            $state = true;
1670
        } else if (!$data && $state === null) {
1671
            $state = false;
1672
        }
1673
    }
1674
}
1675
 
1676
/**
1677
 * Aggregate courses completions. This function is called when activity completion status is updated
1678
 * for single user. Also when regular completion task runs it aggregates completions for all courses and users.
1679
 *
1680
 * @param int $coursecompletionid Course completion ID to update (if 0 - update for all courses and users)
1681
 * @param bool $mtraceprogress To output debug info
1682
 * @since Moodle 4.0
1683
 */
1684
function aggregate_completions(int $coursecompletionid, bool $mtraceprogress = false) {
1685
    global $DB;
1686
 
1687
    if (!$coursecompletionid && $mtraceprogress) {
1688
        mtrace('Aggregating completions');
1689
    }
1690
    // Save time started.
1691
    $timestarted = time();
1692
 
1693
    // Grab all criteria and their associated criteria completions.
1694
    $sql = "SELECT DISTINCT c.id AS courseid, cr.id AS criteriaid, cco.userid, cr.criteriatype, ccocr.timecompleted
1695
                       FROM {course_completion_criteria} cr
1696
                 INNER JOIN {course} c ON cr.course = c.id
1697
                 INNER JOIN {course_completions} cco ON cco.course = c.id
1698
                  LEFT JOIN {course_completion_crit_compl} ccocr
1699
                         ON ccocr.criteriaid = cr.id AND cco.userid = ccocr.userid
1700
                      WHERE c.enablecompletion = 1
1701
                        AND cco.timecompleted IS NULL
1702
                        AND cco.reaggregate > 0";
1703
 
1704
    if ($coursecompletionid) {
1705
        $sql .= " AND cco.id = ?";
1706
        $param = $coursecompletionid;
1707
    } else {
1708
        $sql .= " AND cco.reaggregate < ? ORDER BY courseid, cco.userid";
1709
        $param = $timestarted;
1710
    }
1711
    $rs = $DB->get_recordset_sql($sql, [$param]);
1712
 
1713
    // Check if result is empty.
1714
    if (!$rs->valid()) {
1715
        $rs->close();
1716
        return;
1717
    }
1718
 
1719
    $currentuser = null;
1720
    $currentcourse = null;
1721
    $completions = [];
1722
    while (1) {
1723
        // Grab records for current user/course.
1724
        foreach ($rs as $record) {
1725
            // If we are still grabbing the same users completions.
1726
            if ($record->userid === $currentuser && $record->courseid === $currentcourse) {
1727
                $completions[$record->criteriaid] = $record;
1728
            } else {
1729
                break;
1730
            }
1731
        }
1732
 
1733
        // Aggregate.
1734
        if (!empty($completions)) {
1735
            if (!$coursecompletionid && $mtraceprogress) {
1736
                mtrace('Aggregating completions for user ' . $currentuser . ' in course ' . $currentcourse);
1737
            }
1738
 
1739
            // Get course info object.
1740
            $info = new \completion_info((object)['id' => $currentcourse]);
1741
 
1742
            // Setup aggregation.
1743
            $overall = $info->get_aggregation_method();
1744
            $activity = $info->get_aggregation_method(COMPLETION_CRITERIA_TYPE_ACTIVITY);
1745
            $prerequisite = $info->get_aggregation_method(COMPLETION_CRITERIA_TYPE_COURSE);
1746
            $role = $info->get_aggregation_method(COMPLETION_CRITERIA_TYPE_ROLE);
1747
 
1748
            $overallstatus = null;
1749
            $activitystatus = null;
1750
            $prerequisitestatus = null;
1751
            $rolestatus = null;
1752
 
1753
            // Get latest timecompleted.
1754
            $timecompleted = null;
1755
 
1756
            // Check each of the criteria.
1757
            foreach ($completions as $params) {
1758
                $timecompleted = max($timecompleted, $params->timecompleted);
1759
                $completion = new \completion_criteria_completion((array)$params, false);
1760
 
1761
                // Handle aggregation special cases.
1762
                if ($params->criteriatype == COMPLETION_CRITERIA_TYPE_ACTIVITY) {
1763
                    completion_cron_aggregate($activity, $completion->is_complete(), $activitystatus);
1764
                } else if ($params->criteriatype == COMPLETION_CRITERIA_TYPE_COURSE) {
1765
                    completion_cron_aggregate($prerequisite, $completion->is_complete(), $prerequisitestatus);
1766
                } else if ($params->criteriatype == COMPLETION_CRITERIA_TYPE_ROLE) {
1767
                    completion_cron_aggregate($role, $completion->is_complete(), $rolestatus);
1768
                } else {
1769
                    completion_cron_aggregate($overall, $completion->is_complete(), $overallstatus);
1770
                }
1771
            }
1772
 
1773
            // Include role criteria aggregation in overall aggregation.
1774
            if ($rolestatus !== null) {
1775
                completion_cron_aggregate($overall, $rolestatus, $overallstatus);
1776
            }
1777
 
1778
            // Include activity criteria aggregation in overall aggregation.
1779
            if ($activitystatus !== null) {
1780
                completion_cron_aggregate($overall, $activitystatus, $overallstatus);
1781
            }
1782
 
1783
            // Include prerequisite criteria aggregation in overall aggregation.
1784
            if ($prerequisitestatus !== null) {
1785
                completion_cron_aggregate($overall, $prerequisitestatus, $overallstatus);
1786
            }
1787
 
1788
            // If aggregation status is true, mark course complete for user.
1789
            if ($overallstatus) {
1790
                if (!$coursecompletionid && $mtraceprogress) {
1791
                    mtrace('Marking complete');
1792
                }
1793
 
1794
                $ccompletion = new \completion_completion([
1795
                    'course' => $params->courseid,
1796
                    'userid' => $params->userid
1797
                ]);
1798
                $ccompletion->mark_complete($timecompleted);
1799
            }
1800
        }
1801
 
1802
        // If this is the end of the recordset, break the loop.
1803
        if (!$rs->valid()) {
1804
            $rs->close();
1805
            break;
1806
        }
1807
 
1808
        // New/next user, update user details, reset completions.
1809
        $currentuser = $record->userid;
1810
        $currentcourse = $record->courseid;
1811
        $completions = [];
1812
        $completions[$record->criteriaid] = $record;
1813
    }
1814
 
1815
    // Mark all users as aggregated.
1816
    if ($coursecompletionid) {
1817
        $select = "reaggregate > 0 AND id = ?";
1818
        $param = $coursecompletionid;
1819
    } else {
1820
        $select = "reaggregate > 0 AND reaggregate < ?";
1821
        $param = $timestarted;
1822
        if (PHPUNIT_TEST) {
1823
            // MDL-33320: for instant completions we need aggregate to work in a single run.
1824
            $DB->set_field('course_completions', 'reaggregate', $timestarted - 2);
1825
        }
1826
    }
1827
    $DB->set_field_select('course_completions', 'reaggregate', 0, $select, [$param]);
1828
}