MDL-67613 availability_completion: add previous activity condition
[moodle.git] / availability / condition / completion / classes / condition.php
CommitLineData
e01efa2c 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 * Activity completion condition.
19 *
20 * @package availability_completion
21 * @copyright 2014 The Open University
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24
25namespace availability_completion;
26
c54b183c
FR
27use cache;
28use core_availability\info;
29use core_availability\info_module;
30use core_availability\info_section;
31use stdClass;
32
e01efa2c 33defined('MOODLE_INTERNAL') || die();
34
35require_once($CFG->libdir . '/completionlib.php');
36
37/**
38 * Activity completion condition.
39 *
40 * @package availability_completion
41 * @copyright 2014 The Open University
42 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
43 */
44class condition extends \core_availability\condition {
c54b183c
FR
45
46 /** @var int previous module cm value used to calculate relative completions */
47 public const OPTION_PREVIOUS = -1;
48
e01efa2c 49 /** @var int ID of module that this depends on */
50 protected $cmid;
51
c54b183c
FR
52 /** @var array IDs of the current module and section */
53 protected $selfids;
54
e01efa2c 55 /** @var int Expected completion type (one of the COMPLETE_xx constants) */
56 protected $expectedcompletion;
57
c54b183c
FR
58 /** @var array Array of previous cmids used to calculate relative completions */
59 protected $modfastprevious = array();
60
61 /** @var array Array of cmids previous to each course section */
62 protected $sectionfastprevious = array();
63
e01efa2c 64 /** @var array Array of modules used in these conditions for course */
65 protected static $modsusedincondition = array();
66
67 /**
68 * Constructor.
69 *
5cad8d35
AA
70 * @param \stdClass $structure Data structure from JSON decode
71 * @throws \coding_exception If invalid data structure.
e01efa2c 72 */
73 public function __construct($structure) {
74 // Get cmid.
729a6c56
DM
75 if (isset($structure->cm) && is_number($structure->cm)) {
76 $this->cmid = (int)$structure->cm;
e01efa2c 77 } else {
78 throw new \coding_exception('Missing or invalid ->cm for completion condition');
79 }
e01efa2c 80 // Get expected completion.
81 if (isset($structure->e) && in_array($structure->e,
82 array(COMPLETION_COMPLETE, COMPLETION_INCOMPLETE,
83 COMPLETION_COMPLETE_PASS, COMPLETION_COMPLETE_FAIL))) {
84 $this->expectedcompletion = $structure->e;
85 } else {
86 throw new \coding_exception('Missing or invalid ->e for completion condition');
87 }
88 }
89
c54b183c
FR
90 /**
91 * Saves tree data back to a structure object.
92 *
93 * @return stdClass Structure object (ready to be made into JSON format)
94 */
95 public function save(): stdClass {
e01efa2c 96 return (object)array('type' => 'completion',
97 'cm' => $this->cmid, 'e' => $this->expectedcompletion);
98 }
99
06c06038 100 /**
101 * Returns a JSON object which corresponds to a condition of this type.
102 *
103 * Intended for unit testing, as normally the JSON values are constructed
104 * by JavaScript code.
105 *
106 * @param int $cmid Course-module id of other activity
107 * @param int $expectedcompletion Expected completion value (COMPLETION_xx)
108 * @return stdClass Object representing condition
109 */
c54b183c 110 public static function get_json(int $cmid, int $expectedcompletion): stdClass {
06c06038 111 return (object)array('type' => 'completion', 'cm' => (int)$cmid,
112 'e' => (int)$expectedcompletion);
113 }
114
c54b183c
FR
115 /**
116 * Determines whether a particular item is currently available
117 * according to this availability condition.
118 *
119 * @see \core_availability\tree_node\update_after_restore
120 *
121 * @param bool $not Set true if we are inverting the condition
122 * @param info $info Item we're checking
123 * @param bool $grabthelot Performance hint: if true, caches information
124 * required for all course-modules, to make the front page and similar
125 * pages work more quickly (works only for current user)
126 * @param int $userid User ID to check availability for
127 * @return bool True if available
128 */
129 public function is_available($not, info $info, $grabthelot, $userid): bool {
130 list($selfcmid, $selfsectionid) = $this->get_selfids($info);
131 $cmid = $this->get_cmid($info->get_course(), $selfcmid, $selfsectionid);
e01efa2c 132 $modinfo = $info->get_modinfo();
133 $completion = new \completion_info($modinfo->get_course());
c54b183c 134 if (!array_key_exists($cmid, $modinfo->cms) || $modinfo->cms[$cmid]->deletioninprogress) {
e01efa2c 135 // If the cmid cannot be found, always return false regardless
136 // of the condition or $not state. (Will be displayed in the
137 // information message.)
138 $allow = false;
139 } else {
140 // The completion system caches its own data so no caching needed here.
c54b183c 141 $completiondata = $completion->get_data((object)array('id' => $cmid),
e01efa2c 142 $grabthelot, $userid, $modinfo);
143
144 $allow = true;
145 if ($this->expectedcompletion == COMPLETION_COMPLETE) {
146 // Complete also allows the pass, fail states.
147 switch ($completiondata->completionstate) {
148 case COMPLETION_COMPLETE:
149 case COMPLETION_COMPLETE_FAIL:
150 case COMPLETION_COMPLETE_PASS:
151 break;
152 default:
153 $allow = false;
154 }
155 } else {
156 // Other values require exact match.
157 if ($completiondata->completionstate != $this->expectedcompletion) {
158 $allow = false;
159 }
160 }
161
162 if ($not) {
163 $allow = !$allow;
164 }
165 }
166
167 return $allow;
168 }
169
c54b183c
FR
170 /**
171 * Return current item IDs (cmid and sectionid).
172 *
173 * @param info $info
174 * @return int[] with [0] => cmid/null, [1] => sectionid/null
175 */
176 public function get_selfids(info $info): array {
177 if (isset($this->selfids)) {
178 return $this->selfids;
179 }
180 if ($info instanceof info_module) {
181 $cminfo = $info->get_course_module();
182 if (!empty($cminfo->id)) {
183 $this->selfids = array($cminfo->id, null);
184 return $this->selfids;
185 }
186 }
187 if ($info instanceof info_section) {
188 $section = $info->get_section();
189 if (!empty($section->id)) {
190 $this->selfids = array(null, $section->id);
191 return $this->selfids;
192 }
193
194 }
195 return array(null, null);
196 }
197
198 /**
199 * Get the cmid referenced in the access restriction.
200 *
201 * @param stdClass $course course object
202 * @param int|null $selfcmid current course-module ID or null
203 * @param int|null $selfsectionid current course-section ID or null
204 * @return int|null cmid or null if no referenced cm is found
205 */
206 public function get_cmid(stdClass $course, ?int $selfcmid, ?int $selfsectionid): ?int {
207 if ($this->cmid > 0) {
208 return $this->cmid;
209 }
210 // If it's a relative completion, load fast browsing.
211 if ($this->cmid == self::OPTION_PREVIOUS) {
212 $prevcmid = $this->get_previous_cmid($course, $selfcmid, $selfsectionid);
213 if ($prevcmid) {
214 return $prevcmid;
215 }
216 }
217 return null;
218 }
219
220 /**
221 * Return the previous CM ID of an specific course-module or course-section.
222 *
223 * @param stdClass $course course object
224 * @param int|null $selfcmid course-module ID or null
225 * @param int|null $selfsectionid course-section ID or null
226 * @return int|null
227 */
228 private function get_previous_cmid(stdClass $course, ?int $selfcmid, ?int $selfsectionid): ?int {
229 $this->load_course_structure($course);
230 if (isset($this->modfastprevious[$selfcmid])) {
231 return $this->modfastprevious[$selfcmid];
232 }
233 if (isset($this->sectionfastprevious[$selfsectionid])) {
234 return $this->sectionfastprevious[$selfsectionid];
235 }
236 return null;
237 }
238
239 /**
240 * Loads static information about a course elements previous activities.
241 *
242 * Populates two variables:
243 * - $this->sectionprevious[] course-module previous to a cmid
244 * - $this->sectionfastprevious[] course-section previous to a cmid
245 *
246 * @param stdClass $course course object
247 */
248 private function load_course_structure(stdClass $course): void {
249 // If already loaded we don't need to do anything.
250 if (empty($this->modfastprevious)) {
251 $previouscache = cache::make('availability_completion', 'previous_cache');
252 $this->modfastprevious = $previouscache->get("mod_{$course->id}");
253 $this->sectionfastprevious = $previouscache->get("sec_{$course->id}");
254 }
255
256 if (!empty($this->modfastprevious)) {
257 return;
258 }
259
260 if (empty($this->modfastprevious)) {
261 $this->modfastprevious = array();
262 $sectionprevious = array();
263
264 $modinfo = get_fast_modinfo($course);
265 $lastcmid = 0;
266 foreach ($modinfo->cms as $othercm) {
267 if ($othercm->deletioninprogress) {
268 continue;
269 }
270 // Save first cm of every section.
271 if (!isset($sectionprevious[$othercm->section])) {
272 $sectionprevious[$othercm->section] = $lastcmid;
273 }
274 // Load previous to all cms with completion.
275 if ($othercm->completion == COMPLETION_TRACKING_NONE) {
276 continue;
277 }
278 if ($lastcmid) {
279 $this->modfastprevious[$othercm->id] = $lastcmid;
280 }
281 $lastcmid = $othercm->id;
282 }
283 // Fill empty sections index.
284 $isections = array_reverse($modinfo->get_section_info_all());
285 foreach ($isections as $section) {
286 if (isset($sectionprevious[$section->id])) {
287 $lastcmid = $sectionprevious[$section->id];
288 } else {
289 $sectionprevious[$section->id] = $lastcmid;
290 }
291 }
292 $this->sectionfastprevious = $sectionprevious;
293 $previouscache->set("mod_{$course->id}", $this->modfastprevious);
294 $previouscache->set("sec_{$course->id}", $this->sectionfastprevious);
295 }
296 }
297
e01efa2c 298 /**
299 * Returns a more readable keyword corresponding to a completion state.
300 *
301 * Used to make lang strings easier to read.
302 *
303 * @param int $completionstate COMPLETION_xx constant
304 * @return string Readable keyword
305 */
c54b183c 306 protected static function get_lang_string_keyword(int $completionstate): string {
e01efa2c 307 switch($completionstate) {
308 case COMPLETION_INCOMPLETE:
309 return 'incomplete';
310 case COMPLETION_COMPLETE:
311 return 'complete';
312 case COMPLETION_COMPLETE_PASS:
313 return 'complete_pass';
314 case COMPLETION_COMPLETE_FAIL:
315 return 'complete_fail';
316 default:
317 throw new \coding_exception('Unexpected completion state: ' . $completionstate);
318 }
319 }
320
c54b183c
FR
321 /**
322 * Obtains a string describing this restriction (whether or not
323 * it actually applies).
324 *
325 * @param bool $full Set true if this is the 'full information' view
326 * @param bool $not Set true if we are inverting the condition
327 * @param info $info Item we're checking
328 * @return string Information string (for admin) about all restrictions on
329 * this item
330 */
331 public function get_description($full, $not, info $info): string {
332 global $USER;
333 $str = 'requires_';
334 $course = $info->get_course();
335 list($selfcmid, $selfsectionid) = $this->get_selfids($info);
336 $modname = '';
337 // On ajax duplicate get_fast_modinfo is called before $PAGE->set_context
338 // so we cannot use $PAGE->user_is_editing().
339 $coursecontext = \context_course::instance($course->id);
340 $editing = !empty($USER->editing) && has_capability('moodle/course:manageactivities', $coursecontext);
341 if ($this->cmid == self::OPTION_PREVIOUS && $editing) {
342 // Previous activity name could be inconsistent when editing due to partial page loadings.
343 $str .= 'previous_';
e01efa2c 344 } else {
c54b183c
FR
345 // Get name for module.
346 $cmid = $this->get_cmid($course, $selfcmid, $selfsectionid);
347 $modinfo = $info->get_modinfo();
348 if (!array_key_exists($cmid, $modinfo->cms) || $modinfo->cms[$cmid]->deletioninprogress) {
349 $modname = get_string('missing', 'availability_completion');
350 } else {
351 $modname = '<AVAILABILITY_CMNAME_' . $modinfo->cms[$cmid]->id . '/>';
352 }
e01efa2c 353 }
354
c54b183c 355 // Work out which lang string to use depending on required completion status.
e01efa2c 356 if ($not) {
357 // Convert NOT strings to use the equivalent where possible.
358 switch ($this->expectedcompletion) {
359 case COMPLETION_INCOMPLETE:
c54b183c 360 $str .= self::get_lang_string_keyword(COMPLETION_COMPLETE);
e01efa2c 361 break;
362 case COMPLETION_COMPLETE:
c54b183c 363 $str .= self::get_lang_string_keyword(COMPLETION_INCOMPLETE);
e01efa2c 364 break;
365 default:
366 // The other two cases do not have direct opposites.
c54b183c 367 $str .= 'not_' . self::get_lang_string_keyword($this->expectedcompletion);
e01efa2c 368 break;
369 }
370 } else {
c54b183c 371 $str .= self::get_lang_string_keyword($this->expectedcompletion);
e01efa2c 372 }
373
374 return get_string($str, 'availability_completion', $modname);
375 }
376
c54b183c
FR
377 /**
378 * Obtains a representation of the options of this condition as a string,
379 * for debugging.
380 *
381 * @return string Text representation of parameters
382 */
383 protected function get_debug_string(): string {
e01efa2c 384 switch ($this->expectedcompletion) {
385 case COMPLETION_COMPLETE :
386 $type = 'COMPLETE';
387 break;
388 case COMPLETION_INCOMPLETE :
389 $type = 'INCOMPLETE';
390 break;
391 case COMPLETION_COMPLETE_PASS:
392 $type = 'COMPLETE_PASS';
393 break;
394 case COMPLETION_COMPLETE_FAIL:
395 $type = 'COMPLETE_FAIL';
396 break;
397 default:
398 throw new \coding_exception('Unexpected expected completion');
399 }
c54b183c
FR
400 $cm = $this->cmid;
401 if ($this->cmid == self::OPTION_PREVIOUS) {
402 $cm = 'opprevious';
403 }
404 return 'cm' . $cm . ' ' . $type;
e01efa2c 405 }
406
c54b183c
FR
407 /**
408 * Updates this node after restore, returning true if anything changed.
409 *
410 * @see \core_availability\tree_node\update_after_restore
411 *
412 * @param string $restoreid Restore ID
413 * @param int $courseid ID of target course
414 * @param \base_logger $logger Logger for any warnings
415 * @param string $name Name of this item (for use in warning messages)
416 * @return bool True if there was any change
417 */
418 public function update_after_restore($restoreid, $courseid, \base_logger $logger, $name): bool {
e01efa2c 419 global $DB;
c54b183c
FR
420 $res = false;
421 // If we depend on the previous activity, no translation is needed.
422 if ($this->cmid == self::OPTION_PREVIOUS) {
423 return $res;
424 }
e01efa2c 425 $rec = \restore_dbops::get_backup_ids_record($restoreid, 'course_module', $this->cmid);
426 if (!$rec || !$rec->newitemid) {
427 // If we are on the same course (e.g. duplicate) then we can just
428 // use the existing one.
429 if ($DB->record_exists('course_modules',
430 array('id' => $this->cmid, 'course' => $courseid))) {
c54b183c 431 return $res;
e01efa2c 432 }
433 // Otherwise it's a warning.
434 $this->cmid = 0;
435 $logger->process('Restored item (' . $name .
436 ') has availability condition on module that was not restored',
437 \backup::LOG_WARNING);
438 } else {
439 $this->cmid = (int)$rec->newitemid;
440 }
441 return true;
442 }
443
444 /**
445 * Used in course/lib.php because we need to disable the completion JS if
446 * a completion value affects a conditional activity.
447 *
5cad8d35 448 * @param \stdClass $course Moodle course object
e01efa2c 449 * @param int $cmid Course-module id
450 * @return bool True if this is used in a condition, false otherwise
451 */
c54b183c 452 public static function completion_value_used($course, $cmid): bool {
e01efa2c 453 // Have we already worked out a list of required completion values
454 // for this course? If so just use that.
455 if (!array_key_exists($course->id, self::$modsusedincondition)) {
456 // We don't have data for this course, build it.
457 $modinfo = get_fast_modinfo($course);
458 self::$modsusedincondition[$course->id] = array();
459
460 // Activities.
461 foreach ($modinfo->cms as $othercm) {
462 if (is_null($othercm->availability)) {
463 continue;
464 }
465 $ci = new \core_availability\info_module($othercm);
466 $tree = $ci->get_availability_tree();
467 foreach ($tree->get_all_children('availability_completion\condition') as $cond) {
c54b183c
FR
468 $condcmid = $cond->get_cmid($course, $othercm->id, null);
469 if (!empty($condcmid)) {
470 self::$modsusedincondition[$course->id][$condcmid] = true;
471 }
e01efa2c 472 }
473 }
474
475 // Sections.
476 foreach ($modinfo->get_section_info_all() as $section) {
477 if (is_null($section->availability)) {
478 continue;
479 }
480 $ci = new \core_availability\info_section($section);
481 $tree = $ci->get_availability_tree();
482 foreach ($tree->get_all_children('availability_completion\condition') as $cond) {
c54b183c
FR
483 $condcmid = $cond->get_cmid($course, null, $section->id);
484 if (!empty($condcmid)) {
485 self::$modsusedincondition[$course->id][$condcmid] = true;
486 }
e01efa2c 487 }
488 }
489 }
490 return array_key_exists($cmid, self::$modsusedincondition[$course->id]);
491 }
492
493 /**
494 * Wipes the static cache of modules used in a condition (for unit testing).
495 */
496 public static function wipe_static_cache() {
497 self::$modsusedincondition = array();
498 }
499
500 public function update_dependency_id($table, $oldid, $newid) {
501 if ($table === 'course_modules' && (int)$this->cmid === (int)$oldid) {
502 $this->cmid = $newid;
503 return true;
504 } else {
505 return false;
506 }
507 }
508}