Merge branch 'MDL-78858' of https://github.com/paulholden/moodle
[moodle.git] / completion / classes / progress.php
blobc95352259f5045ea67f46dcfcd159bc550d74482
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.
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/>.
17 /**
18 * Contains class used to return completion progress information.
20 * @package core_completion
21 * @copyright 2017 Mark Nelson <markn@moodle.com>
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 namespace core_completion;
27 defined('MOODLE_INTERNAL') || die();
29 require_once($CFG->libdir . '/completionlib.php');
31 /**
32 * Class used to return completion progress information.
34 * @package core_completion
35 * @copyright 2017 Mark Nelson <markn@moodle.com>
36 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 class progress {
40 /**
41 * Returns the course percentage completed by a certain user, returns null if no completion data is available.
43 * @param \stdClass $course Moodle course object
44 * @param int $userid The id of the user, 0 for the current user
45 * @return null|float The percentage, or null if completion is not supported in the course,
46 * or there are no activities that support completion.
48 public static function get_course_progress_percentage($course, $userid = 0) {
49 global $USER;
51 // Make sure we continue with a valid userid.
52 if (empty($userid)) {
53 $userid = $USER->id;
56 $completion = new \completion_info($course);
58 // First, let's make sure completion is enabled.
59 if (!$completion->is_enabled()) {
60 return null;
63 if (!$completion->is_tracked_user($userid)) {
64 return null;
67 // Before we check how many modules have been completed see if the course has.
68 if ($completion->is_course_complete($userid)) {
69 return 100;
72 // Get the number of modules that support completion.
73 $modules = $completion->get_activities();
74 $count = count($modules);
75 if (!$count) {
76 return null;
79 // Get the number of modules that have been completed.
80 $completed = 0;
81 foreach ($modules as $module) {
82 $data = $completion->get_data($module, true, $userid);
83 if (($data->completionstate == COMPLETION_INCOMPLETE) || ($data->completionstate == COMPLETION_COMPLETE_FAIL)) {
84 $completed += 0;
85 } else {
86 $completed += 1;
90 return ($completed / $count) * 100;