aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/admission/AdmissionRule.class.php
blob: a1741574936177ad7f692900f64ae166757472d0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
<?php

/**
 * AdmissionRule.class.php
 *
 * An abstract representation of rules for course admission.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.
 *
 * @author      Thomas Hackl <thomas.hackl@uni-passau.de>
 * @license     http://www.gnu.org/licenses/gpl-2.0.html GPL version 2
 * @category    Stud.IP
 */

abstract class AdmissionRule
{
    // --- ATTRIBUTES ---

    /**
     * When does the validity end?
     */
    public $endTime = 0;

    /**
     * A unique identifier for this rule.
     */
    public $id = '';

    /**
     * A customizable message that is shown to users that are rejected for admission
     * because of the current rule.
     */
    public $message = '';

    /**
     * default message that is shown to users that are rejected for admission
     * because of the current rule.
     */
    public $default_message = '';

    /**
     * When does the validity start?
     */
    public $startTime = 0;

    /**
     * ID of the CourseSet this admission rule belongs to (is stored here for
     * performance reasons).
     */
    public $courseSetId = '';

    /**
     * courseset siblings of this rule
     */
    public $siblings = [];

    /**
     * Are siblings set manually?
     */
    public $siblings_override = false;

    // --- OPERATIONS ---

    public function __construct($ruleId = '', $courseSetId = '')
    {
        $this->id = $ruleId;
        $this->courseSetId = $courseSetId;
    }

    /**
     * Hook that can be called after the seat distribution on the courseset
     * has completed.
     *
     * @param CourseSet $courseset Current courseset.
     */
    public function afterSeatDistribution($courseset)
    {
        return true;
    }

    /**
     * Checks if we are in the rule validity time frame.
     *
     * @return True if the rule is valid because the time frame applies,
     *         otherwise false.
     */
    public function checkTimeFrame()
    {
        $valid = true;
        // Start time given, but still in the future.
        if ($this->startTime && $this->startTime > time()) {
            $valid = false;
        }
        // End time given, but already past.
        if ($this->endTime && $this->endTime < time()) {
            $valid = false;
        }
        return $valid;
    }

    /**
     * Deletes the admission rule and all associated data.
     */
    public function delete()
    {
        // Delete rule assignment to coursesets.
        $stmt = DBManager::get()->prepare("DELETE FROM `courseset_rule`
            WHERE `rule_id`=?");
        $stmt->execute([$this->id]);
    }

    /**
     * Generate a new unique ID.
     *
     * @param  String tableName
     */
    public function generateId($tableName)
    {
        do {
            $newid = md5(uniqid(get_class($this).microtime(), true));
            $db = DBManager::get()->query("SELECT `rule_id`
                FROM `".$tableName."` WHERE `rule_id`=" . DBManager::get()->quote($newid));
        } while ($db->fetch());
        return $newid;
    }

    /**
     * Gets all users that are matched by thís rule.
     *
     * @return Array An array containing IDs of users who are matched by
     *      this rule.
     */
    public function getAffectedUsers()
    {
        return [];
    }

    /**
     * Reads all available AdmissionRule subclasses and loads their definitions.
     *
     * @param  bool $activeOnly Show only active rules.
     * @return Array
     */
    public static function getAvailableAdmissionRules($activeOnly = true)
    {
        $rules = [];
        $where = ($activeOnly ? " WHERE `active`=1" : "");
        $data = DBManager::get()->query("SELECT * FROM `admissionrules`".$where.
            " ORDER BY `id` ASC");
        while ($current = $data->fetch(PDO::FETCH_ASSOC)) {
            $className = $current['ruletype'];
            if (is_dir($GLOBALS['STUDIP_BASE_PATH'] . DIRECTORY_SEPARATOR . $current['path'])) {
                StudipAutoloader::addAutoloadPath($GLOBALS['STUDIP_BASE_PATH'] . DIRECTORY_SEPARATOR . $current['path']);
                try {
                    $rule = new $className();
                    $rules[$className] = [
                            'id' => $current['id'],
                            'name' => $className::getName(),
                            'description' => $className::getDescription(),
                            'active' => $current['active']
                        ];
                } catch (Exception $e) {
                }
            }
        }
        return $rules;
    }

    /**
     * Get end of validity.
     *
     * @return Integer
     */
    public function getEndTime()
    {
        return $this->endTime;
    }

    /**
     * Subclasses of AdmissionRule can require additional data to be entered on
     * admission (like PasswordAdmission which needs a password for course
     * access). Their corresponding method getInput only returns a HTML form
     * fragment as the output can be concatenated with output from other
     * rules.
     * This static method provides the frame for rendering a full HTML form
     * around the fragments from subclasses.
     *
     * @return Array Start and end templates which wrap input form fragments
     *               from subclasses.
     */
    public static final function getInputFrame()
    {
        return [
            $GLOBALS['template_factory']->open('admission/rules/input_start')->render(),
            $GLOBALS['template_factory']->open('admission/rules/input_end')->render()
        ];
    }

    /**
     * Gets some text that describes what this AdmissionRule (or respective
     * subclass) does.
     */
    public static function getDescription()
    {
        return _("Legt eine Regel fest, die erfüllt sein muss, um sich ".
            "erfolgreich zu einer Menge von Veranstaltungen anmelden zu ".
            "können.");
    }

    public function getInput()
    {
        return '';
    }
    /**
     * Gets the rule ID.
     *
     * @return String This rule's ID.
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Gets the message that is shown to users rejected by this rule.
     *
     * @return String The message.
     */
    public function getMessage()
    {
        return $this->message ?: $this->default_message;
    }

    /**
     * Return this rule's name.
     */
    public static function getName()
    {
        return _("Anmelderegel");
    }

    /**
     * Gets start of validity.
     *
     * @return Integer
     */
    public function getStartTime()
    {
       return $this->startTime;
    }

    /**
     * Gets the template that provides a configuration GUI for this rule.
     *
     * @return String
     */
    public function getTemplate()
    {
        return '';
    }

    /**
     * Internal helper function for loading rule definition from database.
     */
    public function load()
    {
    }

    /**
     * Hook that can be called when the seat distribution on the courseset
     * starts.
     *
     * @param CourseSet The courseset this rule belongs to.
     */
    public function beforeSeatDistribution($courseset)
    {
        return true;
    }

    /**
     * Does the current rule allow the given user to register as participant
     * in the given course?
     *
     * @param  String userId
     * @param  String courseId
     * @return Array
     */
    public function ruleApplies($userId, $courseId)
    {
        return [];
    }

    /**
     * Uses the given data to fill the object values. This can be used
     * as a generic function for storing data if the concrete rule type
     * isn't known in advance.
     *
     * @param Array $data
     * @return AdmissionRule This object.
     */
    public function setAllData($data)
    {
        if ($data['start_date'] && !$data['start_time']) {
            $data['start_time'] = strtotime($data['start_date']);
        }
        if ($data['end_date'] && !$data['end_time']) {
            $data['end_time'] = strtotime($data['end_date'] . ' 23:59:59');
        }
        $this->message = $data['message'];
        $this->startTime = $data['start_time'];
        $this->endTime = $data['end_time'];
        return $this;
    }

    /**
     * Sets a new end time for condition validity.
     *
     * @param  Integer newEndTime
     * @return UserFilter
     */
    public function setEndTime($newEndTime)
    {
        $this->endTime = $newEndTime;
        return $this;
    }

    /**
     * Sets a new message to show to users.
     *
     * @param  String newMessage A new message text.
     * @return AdmissionRule This object
     */
    public function setMessage($newMessage)
    {
        $this->message = $newMessage;
        return $this;
    }

    /**
     * Sets a new start time for condition validity.
     *
     * @param  Integer newStartTime
     * @return UserFilter
     */
    public function setStartTime($newStartTime)
    {
        $this->startTime = $newStartTime;
        return $this;
    }

    /**
     * Helper function for storing rule definition to database.
     */
    public function store()
    {
    }

    /**
     * A textual description of the current rule.
     *
     * @return String
     */
    public function toString()
    {
        return '';
    }

    /**
     * Validates if the given request data is sufficient to configure this rule
     * (e.g. if required values are present).
     *
     * @param  Array Request data
     * @return Array Error messages.
     */
    public function validate($data)
    {
        $errors = [];
        if ($data['start_date'] && $data['end_date'] && strtotime($data['end_date']) < strtotime($data['start_date'])) {
            $errors[] = _('Das Enddatum darf nicht vor dem Startdatum liegen.');
        }
        return $errors;
    }

    /**
     * Standard string representation of this object.
     *
     * @return String
     */
    public function __toString() {
        return $this->toString();
    }

    /**
     * load sibling rules
     *
     */
    public function loadSiblings()
    {
        if ($this->siblings_override) {
            return false;
        }
        $this->siblings = [];
        if ($this->courseSetId != '') {
            $cs = new CourseSet($this->courseSetId);
            foreach ($cs->getAdmissionRules() as $rule_id => $rule) {
                if ($rule->getId() != $this->id) {
                    $this->siblings[$rule_id] = $rule;
                }
            }
        }
    }

    /**
     * get sibling rules
     *
     */
    public function getSiblings()
    {
        $this->loadSiblings();
        return $this->siblings;
    }

    /**
     * set sibling rules
     *
     */
    public function setSiblings($siblings = [])
    {
        $this->siblings_override = true;
        $this->siblings = $siblings;
    }

    /**
     * checks if given admission rule is allowed to be combined with this rule
     *
     * @param AdmissionRule|string $admission_rule
     * @return boolean
     */
    public function isCombinationAllowed($admission_rule)
    {
        if (is_object($admission_rule)) {
            $admission_rule = get_class($admission_rule);
        }
        return AdmissionRuleCompatibility::exists([get_class($this), $admission_rule]);
    }

    public function __clone()
    {
        $this->id = md5(uniqid(get_class($this)));
        $this->courseSetId = null;
    }
} /* end of abstract class AdmissionRule */