aboutsummaryrefslogtreecommitdiff
path: root/lib/admissionrules/coursememberadmission/CourseMemberAdmission.class.php
blob: a502971f0bb07b5daf0f59e458c4a3273cb4c07e (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
<?php

/**
 * CourseMemberAdmission.class.php
 *
 * Specifies a mandatory course membership 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      André Noack <noack@data-quest.de>
 * @license     http://www.gnu.org/licenses/gpl-2.0.html GPL version 2
 * @category    Stud.IP
 */

class CourseMemberAdmission extends AdmissionRule
{
    const MODE_MUST_BE_IN_COURSES = 0;
    const MODE_MAY_NOT_BE_IN_COURSES = 1;
    // --- ATTRIBUTES ---

    /**
     * End of course admission.
     */
    public $courses_to_add = '[]';
    public $modus = '';

    // --- OPERATIONS ---

    /**
     * Standard constructor
     *
     * @param  String $ruleId
     * @param  String e
     */
    public function __construct($ruleId = '', $courseSetId = '')
    {
        parent::__construct($ruleId, $courseSetId);

        if ($ruleId) {
            $this->load();
        } else {
            $this->id = $this->generateId('coursememberadmissions');
        }
    }

    /**
     * Deletes the admission rule and all associated data.
     */
    public function delete()
    {
        parent::delete();

        // Delete rule data.
        DBManager::get()->execute(
            "DELETE FROM `coursememberadmissions` WHERE `rule_id` = ?",
            [$this->id]
        );
    }

    /**
     * Gets some text that describes what this AdmissionRule (or respective
     * subclass) does.
     */
    public static function getDescription()
    {
        return _("Anmelderegeln dieses Typs legen eine Veranstaltung fest, in der die Nutzer bereits eingetragen sein müssen, oder in der sie nicht eingetragen sein dürfen, um sich zu Veranstaltungen des Anmeldesets anmelden zu können.");
    }

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

    /**
     * Gets the template that provides a configuration GUI for this rule.
     *
     * @return String
     */
    public function getTemplate()
    {
        // Open generic admission rule template.
        $tpl = $GLOBALS['template_factory']->open('admission/rules/configure');
        $tpl->set_attribute('rule', $this);

        return $this->getTemplateFactory()->render('configure', [
            'rule'    => $this,
            'tpl'     => $tpl->render(),
            'courses' => $this->getDecodedCourses(),
        ]);
    }

    /**
     * Helper function for loading rule definition from database.
     */
    public function load()
    {
        // Load data.
        $stmt = DBManager::get()->prepare("SELECT *
            FROM `coursememberadmissions` WHERE `rule_id`=? LIMIT 1");
        $stmt->execute([$this->id]);
        if ($current = $stmt->fetchOne()) {
            $this->message = $current['message'];
            $this->startTime = $current['start_time'];
            $this->endTime = $current['end_time'];
            $this->courses_to_add = $current['courses'];
            $this->modus = (int) $current['modus'];
        }
    }

    /**
     * Is admission allowed according to the defined time frame?
     *
     * @param  String $userId
     * @param  String $courseId
     * @return Array
     */
    public function ruleApplies($userId, $courseId)
    {
        $errors = [];
        if ($this->checkTimeFrame()) {
            $courses = $this->getDecodedCourses();
            foreach ($courses as $course) {
                $is_member = CourseMember::exists([$course->id, $userId]);

                if (($this->modus == self::MODE_MUST_BE_IN_COURSES && !$is_member)
                    || ($this->modus == self::MODE_MAY_NOT_BE_IN_COURSES && $is_member)
                ) {
                    $errors[] = $this->getMessage($course);
                }
            }

            // mode: "Mitgliedschaft ist in mindestens einer dieser Veranstaltungen notwendig"
            if ($this->modus == self::MODE_MUST_BE_IN_COURSES && count($errors) < count($courses)) {
                $errors = [];
            }
        }

        return $errors;
    }

    /**
     * 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)
    {
        parent::setAllData($data);

        $this->modus = (int) $data['modus'];
        $this->courses_to_add = json_encode(array_keys($data['courses_to_add']));
        return $this;
    }

    /**
     * Store rule definition to database.
     */
    public function store()
    {
        // Store data.
        $stmt = DBManager::get()->prepare("INSERT INTO `coursememberadmissions`
            (`rule_id`, `message`, `courses`, `modus`, `start_time`,
            `end_time`, `mkdate`, `chdate`) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE `start_time`=VALUES(`start_time`),
            `end_time`=VALUES(`end_time`),message=VALUES(message),courses=VALUES(courses),modus=VALUES(modus), `chdate`=VALUES(`chdate`)");
        $stmt->execute([$this->id, $this->message, $this->courses_to_add, (int)$this->modus, (int)$this->startTime,
            (int)$this->endTime,  time(), time()]);
    }

    /**
     * A textual description of the current rule.
     *
     * @return String
     */
    public function toString()
    {
        return $this->getTemplateFactory()->render('info', [
            'courses' => $this->getDecodedCourses(),
            'rule'    => $this,
            'modus'   => $this->modus,
        ]);
    }

    /**
     * Validates if the given request data is sufficient to configure this rule
     * (e.g. if required values are present).
     *
     * @param  Array $data Request data
     * @return Array Error messages.
     */
    public function validate($data)
    {
        $errors = parent::validate($data);
        if (!$data['courses_to_add']) {
            $errors[] = _('Bitte wählen Sie eine Veranstaltung aus.');
        }
        return $errors;
    }

    public function getMessage($course = null)
    {
        $message = parent::getMessage();

        if ($course) {
            return sprintf($message, $course->getFullName('number-name'));
        } else {
            return $message;
        }
    }

    private function getDecodedCourses()
    {
        $decoded_courses = json_decode($this->courses_to_add, true);
        if (!$decoded_courses) {
            return [];
        }
        return Course::findMany($decoded_courses);
    }

    public function getValidityPeriod(): string
    {
        if ($this->getStartTime() && $this->getEndTime()) {
            return sprintf(
                _('Diese Regel gilt von %s bis %s.'),
                strftime('%d.%m.%Y %H:%M', $this->getStartTime()),
                strftime('%d.%m.%Y %H:%M', $this->getEndTime())
            );
        }

        if ($this->getStartTime() && !$this->getEndTime()) {
            return sprintf(
                _('Diese Regel gilt ab %s.'),
                strftime('%d.%m.%Y %H:%M', $this->getStartTime())
            );
        }

        if (!$this->getStartTime() && $this->getEndTime()) {
            return sprintf(
                _('Diese Regel gilt bis %s.'),
                strftime('%d.%m.%Y %H:%M', $this->getEndTime())
            );
        }

        return '';
    }

    private function getTemplateFactory(): Flexi_TemplateFactory
    {
        return new Flexi_TemplateFactory(__DIR__ . '/templates/');
    }
}