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