MDL-58267 completion: allow to set default activity completion
[moodle.git] / completion / classes / manager.php
CommitLineData
0b620801
AG
1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
18/**
19 * Bulk activity completion manager class
20 *
21 * @package core_completion
22 * @category completion
23 * @copyright 2017 Adrian Greeve
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 */
26
27namespace core_completion;
28
29use stdClass;
e8a71f85 30use context_course;
7f53e8aa 31use cm_info;
0b620801
AG
32
33/**
34 * Bulk activity completion manager class
35 *
36 * @package core_completion
37 * @category completion
38 * @copyright 2017 Adrian Greeve
39 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
40 */
41class manager {
42
43 protected $courseid;
44
45 public function __construct($courseid) {
46 $this->courseid = $courseid;
47 }
48
49 /**
50 * Gets the data (context) to be used with the bulkactivitycompletion template.
51 *
52 * @return stdClass data for use with the bulkactivitycompletion template.
53 */
54 public function get_activities_and_headings() {
55 global $OUTPUT;
56 $moduleinfo = get_fast_modinfo($this->courseid);
57 $sections = $moduleinfo->get_sections();
58 $data = new stdClass;
59 $data->courseid = $this->courseid;
60 $data->sesskey = sesskey();
61 $data->helpicon = $OUTPUT->help_icon('temphelp', 'moodle');
62 $data->sections = [];
63 foreach ($sections as $sectionnumber => $section) {
64 $sectioninfo = $moduleinfo->get_section_info($sectionnumber);
65
66 $sectionobject = new stdClass();
67 $sectionobject->sectionnumber = $sectionnumber;
68 $sectionobject->name = get_section_name($this->courseid, $sectioninfo);
7f53e8aa 69 $sectionobject->activities = $this->get_activities($section, true);
0cbc248d
MG
70 $data->sections[] = $sectionobject;
71 }
72 return $data;
73 }
0b620801 74
0cbc248d
MG
75 /**
76 * Gets the data (context) to be used with the activityinstance template
77 *
78 * @param array $cmids list of course module ids
79 * @param bool $withcompletiondetails include completion details
7f53e8aa 80 * @return array
0cbc248d
MG
81 */
82 public function get_activities($cmids, $withcompletiondetails = false) {
83 $moduleinfo = get_fast_modinfo($this->courseid);
84 $activities = [];
85 foreach ($cmids as $cmid) {
86 $mod = $moduleinfo->get_cm($cmid);
87 if (!$mod->uservisible) {
88 continue;
89 }
90 $moduleobject = new stdClass();
91 $moduleobject->cmid = $cmid;
92 $moduleobject->modname = $mod->get_formatted_name();
93 $moduleobject->icon = $mod->get_icon_url()->out();
94 $moduleobject->url = $mod->url;
95 $moduleobject->canmanage = $withcompletiondetails && self::can_edit_bulk_completion($this->courseid, $mod);
96
97 // Get activity completion information.
98 if ($moduleobject->canmanage) {
7f53e8aa 99 $moduleobject->completionstatus = $this->get_completion_detail($mod);
0cbc248d
MG
100 } else {
101 $moduleobject->completionstatus = ['icon' => null, 'string' => null];
0b620801 102 }
0cbc248d
MG
103
104 $activities[] = $moduleobject;
0b620801 105 }
7f53e8aa 106 return $activities;
0b620801
AG
107 }
108
7f53e8aa
MG
109
110 /**
111 * Get completion information on the selected module or module type
112 *
113 * @param cm_info|stdClass $mod either instance of cm_info (with 'customcompletionrules' in customdata) or
114 * object with fields ->completion, ->completionview, ->completionexpected, ->completionusegrade
115 * and ->customdata['customcompletionrules']
116 * @return array
117 */
118 private function get_completion_detail($mod) {
0b620801
AG
119 global $OUTPUT;
120 $strings = [];
121 switch ($mod->completion) {
7f53e8aa 122 case COMPLETION_TRACKING_NONE:
0b620801
AG
123 $strings['string'] = get_string('none');
124 break;
125
7f53e8aa 126 case COMPLETION_TRACKING_MANUAL:
0b620801
AG
127 $strings['string'] = get_string('manual');
128 $strings['icon'] = $OUTPUT->pix_url('i/completion-manual-enabled')->out();
129 break;
130
7f53e8aa 131 case COMPLETION_TRACKING_AUTOMATIC:
0b620801
AG
132 $strings['string'] = get_string('withconditions');
133
134 // Get the descriptions for all the active completion rules for the module.
7f53e8aa 135 if ($ruledescriptions = $this->get_completion_active_rule_descriptions($mod)) {
0b620801
AG
136 foreach ($ruledescriptions as $ruledescription) {
137 $strings['string'] .= \html_writer::empty_tag('br') . $ruledescription;
138 }
139 }
140
141 $strings['icon'] = $OUTPUT->pix_url('i/completion-auto-enabled')->out();
142 break;
143
144 default:
145 $strings['string'] = get_string('none');
146 break;
147 }
148 return $strings;
149 }
150
7f53e8aa
MG
151 /**
152 * Get the descriptions for all active conditional completion rules for the current module.
153 *
154 * @param cm_info|stdClass $moduledata either instance of cm_info (with 'customcompletionrules' in customdata) or
155 * object with fields ->completion, ->completionview, ->completionexpected, ->completionusegrade
156 * and ->customdata['customcompletionrules']
157 * @return array $activeruledescriptions an array of strings describing the active completion rules.
158 */
159 protected function get_completion_active_rule_descriptions($moduledata) {
160 $activeruledescriptions = [];
161
162 // Generate the description strings for the core conditional completion rules (if set).
163 if (!empty($moduledata->completionview)) {
164 $activeruledescriptions[] = get_string('completionview_desc', 'core_completion');
165 }
166 if ($moduledata instanceof cm_info && !is_null($moduledata->completiongradeitemnumber) ||
167 ($moduledata instanceof stdClass && !empty($moduledata->completionusegrade))) {
168 $activeruledescriptions[] = get_string('completionusegrade_desc', 'core_completion');
169 }
170
171 // Now, ask the module to provide descriptions for its custom conditional completion rules.
172 if ($customruledescriptions = component_callback($moduledata->modname,
173 'get_completion_active_rule_descriptions', [$moduledata])) {
174 $activeruledescriptions = array_merge($activeruledescriptions, $customruledescriptions);
175 }
176
177 if (!empty($moduledata->completionexpected)) {
178 $activeruledescriptions[] = get_string('completionexpecteddesc', 'core_completion',
179 userdate($moduledata->completionexpected));
180 }
181
182 return $activeruledescriptions;
183 }
184
e8a71f85 185 public function get_activities_and_resources() {
7f53e8aa
MG
186 global $DB, $OUTPUT, $CFG;
187 require_once($CFG->dirroot.'/course/lib.php');
188
e8a71f85
AG
189 // Get enabled activities and resources.
190 $modules = $DB->get_records('modules', ['visible' => 1], 'name ASC');
191 $data = new stdClass();
192 $data->courseid = $this->courseid;
193 $data->sesskey = sesskey();
194 $data->helpicon = $OUTPUT->help_icon('temphelp', 'moodle');
195 // Add icon information.
196 $data->modules = array_values($modules);
197 $coursecontext = context_course::instance($this->courseid);
7f53e8aa
MG
198 $canmanage = has_capability('moodle/course:manageactivities', $coursecontext);
199 $course = get_course($this->courseid);
e8a71f85
AG
200 foreach ($data->modules as $module) {
201 $module->icon = $OUTPUT->pix_url('icon', $module->name)->out();
7f53e8aa
MG
202 $module->formattedname = format_string(get_string('modulenameplural', 'mod_' . $module->name),
203 true, ['context' => $coursecontext]);
204 $module->canmanage = $canmanage && \course_allowed_module($course, $module->name);
205 $defaults = self::get_default_completion($course, $module, false);
206 $defaults->modname = $module->name;
207 $module->completionstatus = $this->get_completion_detail($defaults);
e8a71f85
AG
208 }
209
210 return $data;
211 }
212
0cbc248d
MG
213 /**
214 * Checks if current user can edit activity completion
215 *
216 * @param int|stdClass $courseorid
217 * @param \cm_info|null $cm if specified capability for a given coursemodule will be check,
218 * if not specified capability to edit at least one activity is checked.
219 */
220 public static function can_edit_bulk_completion($courseorid, $cm = null) {
221 if ($cm) {
222 return $cm->uservisible && has_capability('moodle/course:manageactivities', $cm->context);
223 }
224 $coursecontext = context_course::instance(is_object($courseorid) ? $courseorid->id : $courseorid);
225 if (has_capability('moodle/course:manageactivities', $coursecontext)) {
226 return true;
227 }
228 $modinfo = get_fast_modinfo($courseorid);
229 foreach ($modinfo->cms as $mod) {
230 if ($mod->uservisible && has_capability('moodle/course:manageactivities', $mod->context)) {
231 return true;
232 }
233 }
234 return false;
235 }
06cdda46
MG
236
237 /**
238 * Applies completion from the bulk edit form to all selected modules
239 *
240 * @param stdClass $data data received from the core_completion_bulkedit_form
7f53e8aa 241 * @param bool $updateinstances if we need to update the instance tables of the module (i.e. 'assign', 'forum', etc.) -
06cdda46
MG
242 * if no module-specific completion rules were added to the form, update of the module table is not needed.
243 */
244 public function apply_completion($data, $updateinstances) {
245 $updated = [];
246 $modinfo = get_fast_modinfo($this->courseid);
247
248 $cmids = $data->cmid;
249
250 $data = (array)$data;
251 unset($data['id']); // This is a course id, we don't want to confuse it with cmid or instance id.
252 unset($data['cmid']);
253 unset($data['submitbutton']);
254
255 foreach ($cmids as $cmid) {
256 $cm = $modinfo->get_cm($cmid);
257 if (self::can_edit_bulk_completion($this->courseid, $cm) && $this->apply_completion_cm($cm, $data, $updateinstances)) {
258 $updated[] = $cm->id;
259 }
260 }
261 if ($updated) {
262 // Now that modules are fully updated, also update completion data if required.
263 // This will wipe all user completion data and recalculate it.
264 rebuild_course_cache($this->courseid, true);
265 $modinfo = get_fast_modinfo($this->courseid);
266 $completion = new \completion_info($modinfo->get_course());
267 foreach ($updated as $cmid) {
268 $completion->reset_all_state($modinfo->get_cm($cmid));
269 }
270 }
271 }
272
273 /**
274 * Applies new completion rules to one course module
275 *
276 * @param \cm_info $cm
277 * @param array $data
278 * @param bool $updateinstance if we need to update the instance table of the module (i.e. 'assign', 'forum', etc.) -
279 * if no module-specific completion rules were added to the form, update of the module table is not needed.
280 * @return bool if module was updated
281 */
282 protected function apply_completion_cm(\cm_info $cm, $data, $updateinstance) {
283 global $DB;
284
285 $defaults = ['completion' => COMPLETION_DISABLED, 'completionview' => COMPLETION_VIEW_NOT_REQUIRED,
286 'completionexpected' => 0, 'completiongradeitemnumber' => null];
287
288 if ($cm->completion == $data['completion'] && $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
289 // If old and new completion are either both "manual" or both "none" - no changes are needed.
290 return false;
291 }
292
293 $data += ['completion' => $cm->completion,
294 'completionexpected' => $cm->completionexpected,
295 'completionview' => $cm->completionview];
296
297 if (array_key_exists('completionusegrade', $data)) {
298 // Convert the 'use grade' checkbox into a grade-item number: 0 if checked, null if not.
299 $data['completiongradeitemnumber'] = !empty($data['completionusegrade']) ? 0 : null;
300 unset($data['completionusegrade']);
301 } else {
302 $data['completiongradeitemnumber'] = $cm->completiongradeitemnumber;
303 }
304
305 // Update module instance table.
306 if ($updateinstance) {
307 $moddata = ['id' => $cm->instance, 'timemodified' => time()] + array_diff_key($data, $defaults);
308 $DB->update_record($cm->modname, $moddata);
309 }
310
311 // Update course modules table.
312 $cmdata = ['id' => $cm->id, 'timemodified' => time()] + array_intersect_key($data, $defaults);
313 $DB->update_record('course_modules', $cmdata);
314
315 \core\event\course_module_updated::create_from_cm($cm, $cm->context)->trigger();
316
317 \core\notification::add(get_string('completionupdated', 'completion', $cm->get_formatted_name()),
318 \core\notification::SUCCESS);
319 return true;
320 }
321
7f53e8aa
MG
322
323 /**
324 * Saves default completion from edit form to all selected module types
325 *
326 * @param stdClass $data data received from the core_completion_bulkedit_form
327 * @param bool $updatecustomrules if we need to update the custom rules of the module -
328 * if no module-specific completion rules were added to the form, update of the module table is not needed.
329 */
330 public function apply_default_completion($data, $updatecustomrules) {
331 global $DB;
332
333 $courseid = $data->id;
334 $coursecontext = context_course::instance($courseid);
335 if (!$modids = $data->modids) {
336 return;
337 }
338 $defaults = ['completion' => COMPLETION_DISABLED, 'completionview' => COMPLETION_VIEW_NOT_REQUIRED,
339 'completionexpected' => 0, 'completionusegrade' => 0];
340
341 $data = (array)$data;
342
343 if ($updatecustomrules) {
344 $customdata = array_diff_key($data, $defaults);
345 $data['customrules'] = $customdata ? json_encode($customdata) : null;
346 $defaults['customrules'] = null;
347 }
348 $data = array_intersect_key($data, $defaults);
349
350 // Get names of the affected modules.
351 list($modidssql, $params) = $DB->get_in_or_equal($modids);
352 $params[] = 1;
353 $modules = $DB->get_records_select_menu('modules', 'id ' . $modidssql . ' and visible = ?', $params, '', 'id, name');
354
355 foreach ($modids as $modid) {
356 if (!array_key_exists($modid, $modules)) {
357 continue;
358 }
359 if ($defaultsid = $DB->get_field('course_completion_defaults', 'id', ['course' => $courseid, 'module' => $modid])) {
360 $DB->update_record('course_completion_defaults', $data + ['id' => $defaultsid]);
361 } else {
362 $defaultsid = $DB->insert_record('course_completion_defaults', $data + ['course' => $courseid, 'module' => $modid]);
363 }
364 // Trigger event.
365 \core\event\completion_defaults_updated::create([
366 'objectid' => $defaultsid,
367 'context' => $coursecontext,
368 'other' => ['modulename' => $modules[$modid]],
369 ])->trigger();
370 // Add notification.
371 \core\notification::add(get_string('defaultcompletionupdated', 'completion',
372 get_string("modulenameplural", $modules[$modid])), \core\notification::SUCCESS);
373 }
374 }
375
376 /**
377 * Returns default completion rules for given module type in the given course
378 *
379 * @param stdClass $course
380 * @param stdClass $module
381 * @param bool $flatten if true all module custom completion rules become properties of the same object,
382 * otherwise they can be found as array in ->customdata['customcompletionrules']
383 * @return stdClass
384 */
385 public static function get_default_completion($course, $module, $flatten = true) {
386 global $DB, $CFG;
387 if ($data = $DB->get_record('course_completion_defaults', ['course' => $course->id, 'module' => $module->id],
388 'completion, completionview, completionexpected, completionusegrade, customrules')) {
389 if ($data->customrules && ($customrules = @json_decode($data->customrules, true))) {
390 if ($flatten) {
391 foreach ($customrules as $key => $value) {
392 $data->$key = $value;
393 }
394 } else {
395 $data->customdata['customcompletionrules'] = $customrules;
396 }
397 }
398 unset($data->customrules);
399 } else {
400 $data = new stdClass();
401 $data->completion = COMPLETION_TRACKING_NONE;
402 if ($CFG->completiondefault) {
403 $completion = new \completion_info(get_fast_modinfo($course->id)->get_course());
404 if ($completion->is_enabled() && plugin_supports('mod', $module->name, FEATURE_MODEDIT_DEFAULT_COMPLETION, true)) {
405 $data->completion = COMPLETION_TRACKING_MANUAL;
406 }
407 }
408 }
409 return $data;
410 }
0b620801 411}