• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

ewallah / moodle-availability_relativedate / 21174895749

22 Aug 2025 09:11AM UTC coverage: 99.51% (-0.5%) from 100.0%
21174895749

push

github

rdebleu
workflow

203 of 204 relevant lines covered (99.51%)

170.24 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

99.34
/classes/condition.php
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
 * Date condition.
19
 *
20
 * @package   availability_relativedate
21
 * @copyright eWallah (www.eWallah.net)
22
 * @author    Renaat Debleu <info@eWallah.net>
23
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24
 */
25

26
namespace availability_relativedate;
27

28
use context_course;
29
use core_availability\{info, info_module, info_section};
30
use core\di;
31
use core\clock;
32
use stdClass;
33

34
/**
35
 * relativedate from course start condition.
36
 *
37
 * @package   availability_relativedate
38
 * @copyright eWallah (www.eWallah.net)
39
 * @author    Renaat Debleu <info@eWallah.net>
40
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
41
 */
42
class condition extends \core_availability\condition {
43
    /** @var int relativenumber (how many relative) for condition. */
44
    private $relativenumber;
45

46
    /** @var int relativedwm (what does the date relates to) for condition.
47
     *
48
     * 0 => minutes
49
     * 1 => hours
50
     * 2 => days
51
     * 3 => weeks
52
     * 4 => months
53
     */
54
    private $relativedwm;
55

56
    /** @var int relativestart (what date relates to) for condition.
57
     *
58
     * 1 => After Course start date
59
     * 2 => Before Course end date
60
     * 3 => After User enrolment date
61
     * 4 => After Enrolment method end date
62
     * 5 => After Course End date
63
     * 6 => Before Course start date
64
     * 7 => After completion of an activity
65

66
     */
67
    private $relativestart;
68

69
    /**
70
     * @var int Course module id of the activity used by type 6
71
     */
72
    private $relativecoursemodule;
73

74
    /**
75
     * Constructor.
76
     *
77
     * @param stdClass $structure Data structure from JSON decode.
78
     */
79
    public function __construct($structure) {
80
        $this->relativenumber = property_exists($structure, 'n') ? intval($structure->n) : 1;
744✔
81
        $this->relativedwm = property_exists($structure, 'd') ? intval($structure->d) : 2;
744✔
82
        $this->relativestart = property_exists($structure, 's') ? intval($structure->s) : 1;
744✔
83
        $this->relativecoursemodule = property_exists($structure, 'm') ? intval($structure->m) : 0;
744✔
84
    }
85

86
    /**
87
     * Saves the data.
88
     *
89
     * @return object data structure.
90
     */
91
    public function save() {
92
        return (object)[
144✔
93
            'type' => 'relativedate',
144✔
94
            'n' => intval($this->relativenumber),
144✔
95
            'd' => intval($this->relativedwm),
144✔
96
            's' => intval($this->relativestart),
144✔
97
            'm' => intval($this->relativecoursemodule),
144✔
98
        ];
144✔
99
    }
100

101
    /**
102
     * Determines whether this particular item is currently available.
103
     *
104
     * @param bool $not
105
     * @param info $info
106
     * @param bool $grabthelot
107
     * @param int $userid If set, specifies a different user ID to check availability for
108
     * @return bool True if this item is available to the user, false otherwise
109
     */
110
    public function is_available($not, info $info, $grabthelot, $userid) {
111
        $calc = $this->calc($info->get_course(), $userid);
168✔
112
        if ($calc === 0) {
168✔
113
            // Always not available if for some reason the value could not be calculated.
114
            return false;
24✔
115
        }
116
        $allow = di::get(clock::class)->time() >= $calc;
168✔
117
        if ($not) {
168✔
118
            $allow = !$allow;
168✔
119
        }
120
        return $allow;
168✔
121
    }
122

123
    /**
124
     * Obtains a string describing this restriction (whether or not it actually applies).
125
     *
126
     * @param bool $full Set true if this is the 'full information' view
127
     * @param bool $not Set true if we are inverting the condition
128
     * @param info $info Item we're checking
129
     * @return string Information string (for admin) about all restrictions on this item
130
     */
131
    public function get_description($full, $not, info $info): string {
132
        global $USER;
133
        $course = $info->get_course();
360✔
134
        $capability = has_capability('moodle/course:manageactivities', context_course::instance($course->id));
360✔
135
        $relative = $this->relativestart;
360✔
136
        if ($relative === 2 || $relative === 5) {
360✔
137
            if ((!isset($course->enddate) || (int)$course->enddate === 0) && $capability) {
120✔
138
                return get_string('noenddate', 'availability_relativedate');
24✔
139
            }
140
        }
141
        if ($relative === 2 || $relative === 6) {
360✔
142
            $fromuntil = $not ? 'from' : 'until';
120✔
143
        } else {
144
            $fromuntil = $not ? 'until' : 'from';
264✔
145
        }
146
        $calc = $this->calc($course, $USER->id);
360✔
147
        $brackets = '(' . trim($this->get_debug_string()) . ')';
360✔
148
        if ($calc === 0) {
360✔
149
            return $brackets;
120✔
150
        }
151
        $a = new stdClass();
312✔
152
        $a->rnumber = userdate($calc, get_string('strftimedatetime', 'langconfig'));
312✔
153
        $a->rtime = ($capability && $full) ? $brackets : '';
312✔
154
        $a->rela = '';
312✔
155
        return trim(get_string($fromuntil, 'availability_relativedate', $a));
312✔
156
    }
157

158
    /**
159
     * Obtains a representation of the options of this condition as a string for debugging.
160
     *
161
     * @return string Text representation of parameters
162
     */
163
    protected function get_debug_string() {
164
        // TODO: remove concat.
165
        $modname = '';
576✔
166
        if ($this->relativestart === 7) {
576✔
167
            $modname = ' ';
72✔
168
            if (get_coursemodule_from_id('', $this->relativecoursemodule)) {
72✔
169
                $modname .= \core_availability\condition::description_cm_name($this->relativecoursemodule);
72✔
170
            } else {
171
                $modname .= \html_writer::span(get_string('missing', 'availability_relativedate'), 'alert alert-danger');
×
172
            }
173
        }
174
        return ' ' . $this->relativenumber . ' ' . self::options_dwm($this->relativenumber)[$this->relativedwm] . ' ' .
576✔
175
               self::options_start($this->relativestart) . $modname;
576✔
176
    }
177

178
    /**
179
     * Obtains a the options for days week months.
180
     *
181
     * @param int $i index
182
     * @return string
183
     */
184
    public static function options_start(int $i) {
185
        return match ($i) {
600✔
186
            1 => get_string('datestart', 'availability_relativedate'),
120✔
187
            2 => get_string('dateend', 'availability_relativedate'),
120✔
188
            3 => get_string('dateenrol', 'availability_relativedate'),
120✔
189
            4 => get_string('dateendenrol', 'availability_relativedate'),
120✔
190
            5 => get_string('dateendafter', 'availability_relativedate'),
96✔
191
            6 => get_string('datestartbefore', 'availability_relativedate'),
120✔
192
            7 => get_string('datecompletion', 'availability_relativedate'),
96✔
193
            default => '',
600✔
194
        };
600✔
195
    }
196

197
    /**
198
     * Obtains a the options for hours days weeks months.
199
     *
200
     * @param int $number
201
     * @return array
202
     */
203
    public static function options_dwm($number = 2) {
204
        $s = $number === 1 ? '' : 's';
600✔
205
        return [
600✔
206
            0 => get_string('minute' . $s, 'availability_relativedate'),
600✔
207
            1 => get_string('hour' . $s, 'availability_relativedate'),
600✔
208
            2 => get_string('day' . $s, 'availability_relativedate'),
600✔
209
            3 => get_string('week' . $s, 'availability_relativedate'),
600✔
210
            4 => get_string('month' . $s, 'availability_relativedate'),
600✔
211
        ];
600✔
212
    }
213

214
    /**
215
     * Obtains a the options for hour day week month.
216
     *
217
     * @param int $i
218
     * @return string
219
     */
220
    public static function option_dwm(int $i): string {
221
        return match ($i) {
408✔
222
            0 => 'minute',
72✔
223
            1 => 'hour',
120✔
224
            2 => 'day',
168✔
225
            3 => 'week',
120✔
226
            4 => 'month',
48✔
227
            default => '',
408✔
228
        };
408✔
229
    }
230

231
    /**
232
     * Perform the calculation.
233
     *
234
     * @param stdClass $course
235
     * @param int $userid
236
     * @return int relative date.
237
     */
238
    private function calc($course, $userid): int {
239
        $a = $this->relativenumber;
384✔
240
        $b = $this->option_dwm($this->relativedwm);
384✔
241
        $x = "$a $b";
384✔
242
        switch ($this->relativestart) {
384✔
243
            case 6:
384✔
244
                // Before course start date.
245
                return $this->fixdate("-$x", $course->startdate);
96✔
246
            case 2:
336✔
247
                // Before course end date.
248
                return $this->fixdate("-$x", $course->enddate);
96✔
249
            case 5:
288✔
250
                // After course end date.
251
                return $this->fixdate("+$x", $course->enddate);
72✔
252
            case 3:
240✔
253
                // After latest enrolment start date.
254
                $sql = 'SELECT ue.timestart
96✔
255
                        FROM {user_enrolments} ue
256
                        JOIN {enrol} e on ue.enrolid = e.id
257
                        WHERE e.courseid = :courseid AND ue.userid = :userid AND ue.timestart > 0
258
                        ORDER by ue.timestart DESC';
96✔
259
                $lowest = $this->getlowest($sql, ['courseid' => $course->id, 'userid' => $userid]);
96✔
260
                if ($lowest === 0) {
96✔
261
                    // A teacher or admin without restriction - or a student with no limit set?
262
                    $sql = 'SELECT ue.timecreated
72✔
263
                            FROM {user_enrolments} ue
264
                            JOIN {enrol} e on (e.id = ue.enrolid AND e.courseid = :courseid)
265
                            WHERE ue.userid = :userid
266
                            ORDER by ue.timecreated DESC';
72✔
267
                    $lowest = $this->getlowest($sql, ['courseid' => $course->id, 'userid' => $userid]);
72✔
268
                }
269
                return $this->fixdate("+$x", $lowest);
96✔
270
            case 4:
192✔
271
                // After latest enrolment end date.
272
                $sql = 'SELECT e.enrolenddate
96✔
273
                        FROM {user_enrolments} ue
274
                        JOIN {enrol} e on ue.enrolid = e.id
275
                        WHERE e.courseid = :courseid AND ue.userid = :userid
276
                        ORDER by e.enrolenddate DESC';
96✔
277
                $lowest = $this->getlowest($sql, ['courseid' => $course->id, 'userid' => $userid]);
96✔
278
                return $this->fixdate("+$x", $lowest);
96✔
279
            case 7:
144✔
280
                // Since completion of a module.
281
                $cm = new stdClass();
72✔
282
                $cm->id = $this->relativecoursemodule;
72✔
283
                $cm->course = $course->id;
72✔
284

285
                try {
286
                    $completion = new \completion_info($course);
72✔
287
                    $data = $completion->get_data($cm, false, $userid);
72✔
288
                    return $this->fixdate("+$x", $data->timemodified);
72✔
289
                } catch (\Exception $e) {
24✔
290
                    return 0;
24✔
291
                }
292
        }
293
        // After course start date.
294
        return $this->fixdate("+$x", $course->startdate);
96✔
295
    }
296

297
    /**
298
     * Get the record with the lowest value.
299
     *
300
     * @param string $sql
301
     * @param array $parameters
302
     * @return int lowest value.
303
     */
304
    private function getlowest($sql, $parameters): int {
305
        global $DB;
306
        if ($lowestrec = $DB->get_record_sql($sql, $parameters, IGNORE_MULTIPLE)) {
144✔
307
            $recs = get_object_vars($lowestrec);
120✔
308
            foreach ($recs as $value) {
120✔
309
                return $value;
120✔
310
            }
311
        }
312
        return 0;
96✔
313
    }
314

315

316
    /**
317
     * Keep the original hour.
318
     *
319
     * @param string $calc
320
     * @param int $newdate
321
     * @return int relative date.
322
     */
323
    private function fixdate($calc, $newdate): int {
324
        if ($newdate > 0) {
408✔
325
            $olddate = strtotime($calc, $newdate);
360✔
326
            if ($this->relativedwm > 1) {
360✔
327
                $arr1 = getdate($olddate);
264✔
328
                $arr2 = getdate($newdate);
264✔
329
                return mktime($arr2['hours'], $arr2['minutes'], $arr2['seconds'], $arr1['mon'], $arr1['mday'], $arr1['year']);
264✔
330
            }
331
            return $olddate;
120✔
332
        }
333
        return 0;
120✔
334
    }
335

336
    /**
337
     * We need to know if a completion value affects a conditional activity.
338
     * @param int|stdClass $course Moodle course object
339
     * @param int $cmid Course-module id
340
     * @return bool True if this is used in a condition, false otherwise
341
     */
342
    public static function completion_value_used($course, $cmid): bool {
343
        $courseobj = (is_object($course)) ? $course : get_course($course);
48✔
344
        $modinfo = get_fast_modinfo($courseobj);
48✔
345
        foreach ($modinfo->cms as $othercm) {
48✔
346
            if ($othercm->availability) {
48✔
347
                $info = new info_module($othercm);
48✔
348
                if (self::check_used($info, $cmid)) {
48✔
349
                    return true;
48✔
350
                }
351
            }
352
        }
353
        foreach ($modinfo->get_section_info_all() as $section) {
24✔
354
            if ($section->availability) {
24✔
355
                $info = new info_section($section);
24✔
356
                if (self::check_used($info, $cmid)) {
24✔
357
                    return true;
24✔
358
                }
359
            }
360
        }
361
        return false;
24✔
362
    }
363

364
    /**
365
     * We need to know if a completion value affects a conditional activity.
366
     * @param info $info availability info
367
     * @param int $cmid Course module id
368
     * @return bool True if this is used in a condition, false otherwise
369
     */
370
    public static function check_used(info $info, int $cmid): bool {
371
        $tree = $info->get_availability_tree();
48✔
372
        foreach ($tree->get_all_children('availability_relativedate\condition') as $cond) {
48✔
373
            if ($cond->relativestart === 7 && $cond->relativecoursemodule === $cmid) {
48✔
374
                return true;
48✔
375
            }
376
        }
377
        return false;
24✔
378
    }
379

380
    /**
381
     * Helper for updating ids, implemented for course modules and sections
382
     *
383
     * @param string $table
384
     * @param int $oldid
385
     * @param int $newid
386
     * @return bool
387
     */
388
    public function update_dependency_id($table, $oldid, $newid) {
389
        if ($this->relativestart === 7) {
48✔
390
            if (in_array($table, ['course_modules', 'course_sections'])) {
48✔
391
                if ($this->relativecoursemodule === $oldid) {
48✔
392
                    $this->relativecoursemodule = $newid;
48✔
393
                    return true;
48✔
394
                }
395
            }
396
        }
397
        return false;
24✔
398
    }
399

400
    /**
401
     * Updates this node after restore, returning true if anything changed.
402
     *
403
     * @param string $restoreid Restore ID
404
     * @param int $courseid ID of target course
405
     * @param \base_logger $logger Logger for any warnings
406
     * @param string $name Name of this item (for use in warning messages)
407
     * @return bool True if there was any change
408
     */
409
    public function update_after_restore($restoreid, $courseid, \base_logger $logger, $name): bool {
410
        $rec = \restore_dbops::get_backup_ids_record($restoreid, 'course_module', $this->relativecoursemodule);
72✔
411
        if ($rec) {
72✔
412
            $this->relativecoursemodule = $rec->newitemid;
48✔
413
        } else if (!get_coursemodule_from_id('', $this->relativecoursemodule, $courseid)) {
48✔
414
            $this->relativecoursemodule = 0;
24✔
415
            // We do not find the module, so we issue a warning.
416
            $logger->process(
24✔
417
                "Restored item ($name) has availability condition on module that was not restored",
24✔
418
                \backup::LOG_WARNING
24✔
419
            );
24✔
420
        }
421
        return true;
72✔
422
    }
423
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc