aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/admission/AdmissionUserList.class.php
blob: 570bc62b697e1fb1e827f814538c927bedc44603 (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
<?php

/**
 * AdmissionUserList.class.php
 *
 * Contains users that get different probabilities than others in seat
 * distribution algorithm.
 *
 * 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
 */

class AdmissionUserList
{
    // --- ATTRIBUTES ---

    /**
     * Unique identifier of this list.
     */
    public $id = '';

    /**
     * Conditions for automatic user selection.
     */
    public $conditions = [];

    /**
     * A factor for seat distribution algorithm ("1" means normal algorithm,
     * everything between 0 and 1 decreases the chance to get a seat,
     * everything above 1 increases it.)
     */
    public $factor = 1;

    /**
     * Some name to display for this list.
     */
    public $name = '';

    /**
     * ID of the user who created this list.
     */
    public $ownerId = '';

    /**
     * All user IDs that are on this list.
     */
    public $users = [];

    // --- OPERATIONS ---

    /**
     * Standard constructor.
     *
     * @param String id If this is an existing list, here is its ID.
     * @return This object.
     */
    public function __construct($id='') {
        if ($id) {
            $this->id = $id;
            $this->load();
        }
        return $this;
    }

    /**
     * Adds the given condition to the list.
     *
     * @param  UserFilter condition
     * @return AdmissionUserList
     */
    public function addCondition($condition)
    {
        $this->conditions[$condition->getId()] = $condition;
        return $this;
    }

    /**
     * Adds the given user to the list.
     *
     * @param  String userId
     * @return AdmissionUserList
     */
    public function addUser($userId)
    {
        $this->users[$userId] = true;
        return $this;
    }

    /**
     * Deletes this list.
     */
    public function delete() {
        // Remove user assignments to this list.
        DBManager::get()->exec("DELETE FROM `user_factorlist` WHERE `list_id`='".
            $this->id."'");
        // Remove assigned conditions.
        foreach ($this->conditions as $condition) {
            $condition->delete();
        }
        DBManager::get()->exec("DELETE FROM `user_factorlist` WHERE `list_id`='".
            $this->id."'");
        // Delete list data.
        DBManager::get()->exec("DELETE FROM `admissionfactor` WHERE `list_id`='".
            $this->id."'");
    }

    /**
     * Gets the currently set conditions for automatic user selection.
     *
     * @return Integer
     */
    public function getConditions()
    {
        return $this->conditions;
    }

    /**
     * Gets the currently set manipulation factor for this list.
     *
     * @return Float
     */
    public function getFactor()
    {
        return $this->factor;
    }

    /**
     * Gets the list ID.
     *
     * @return String
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Gets the list name.
     *
     * @return String
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Gets the owner ID.
     *
     * @return String
     */
    public function getOwnerId()
    {
        return $this->ownerId;
    }

    /**
     * Gets all user lists the given user has created.
     *
     * @param  String userId
     * @return array
     */
    public static function getUserLists($userId) {
        $result = [];
        $stmt = DBManager::get()->prepare("SELECT `list_id` FROM `admissionfactor` WHERE ".
            "`owner_id`=? ORDER BY `name` ASC");
        $stmt->execute([$userId]);
        $lists = $stmt->fetchAll(PDO::FETCH_ASSOC);
        foreach ($lists as $list) {
            $result[$list['list_id']] = new AdmissionUserList($list['list_id']);
        }
        return $result;
    }

    /**
     * Gets all assigned user IDs.
     *
     * @param bool $as_objects Whether the users should be returned as objects
     * @return array|User[]
     */
    public function getUsers(bool $as_objects = false)
    {
        if (!$as_objects) {
            return $this->users;
        }

        $result = $this->users;
        User::findEachMany(
            function (User $user) use (&$result) {
                $result[$user->id] = $user;
            },
            array_keys($this->users)
        );
        return array_values($result);
    }

    /**
     * Helper function for loading data from DB.
     */
    public function load()
    {
        // Load basic data.
        $stmt = DBManager::get()->prepare("SELECT `list_id`, `name`,
                CAST(`factor` AS UNSIGNED) AS factor, `owner_id`, `mkdate`, `chdate` 
            FROM `admissionfactor` WHERE `list_id`=? LIMIT 1");
        $stmt->execute([$this->id]);
        if ($current = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $this->factor = $current['factor'];
            $this->name = $current['name'];
            $this->ownerId = $current['owner_id'];
            // Load user IDs.
            $stmt2 = DBManager::get()->prepare("SELECT uf.*
                FROM `user_factorlist` AS uf
                JOIN `auth_user_md5` AS a ON (uf.`user_id`=a.`user_id`)
                WHERE uf.`list_id`=?
                ORDER BY a.`Nachname` ASC, a.`Vorname` ASC, a.`username` ASC");
            $stmt2->execute([$this->id]);
            while ($user = $stmt2->fetch(PDO::FETCH_ASSOC)) {
                $this->users[$user['user_id']] = true;
            }

            // Load selection conditions, if applicable.
            // $stmt2 = DBManager::get()->prepare("SELECT `condition_id` FROM ".
            //     "`condition_factorlist` WHERE `list_id`=? ORDER BY `mkdate` ASC");
            //$stmt2->execute(array($this->id));
            //while ($current = $stmt2->fetch(PDO::FETCH_ASSOC)) {
            //    $this->conditions[$current['condition_id']] =
            //        new UserFilter($current['condition_id']);
            //}
        }
    }

    /**
     * Removes the given condition from the list.
     *
     * @param  String conditionId
     * @return AdmissionUserList
     */
    public function removeCondition($conditionId)
    {
        unset($this->conditions[$conditionId]);
        return $this;
    }

    /**
     * Removes the given user from the list.
     *
     * @param  String userId
     * @return AdmissionUserList
     */
    public function removeUser($userId)
    {
        unset($this->users[$userId]);
        return $this;
    }

    /**
     * Set the conditions to the given set.
     *
     * @param  Array conditions
     * @return AdmissionUserList
     */
    public function setConditions($conditions) {
        $this->conditions = [];
        foreach ($conditions as $condition) {
            $this->addCondition($condition);
        }
        return $this;
    }

    /**
     * Sets a factor.
     *
     * @param float $newFactor The new factor to be set.
     * @return AdmissionUserList
     */
    public function setFactor($newFactor)
    {
        $this->factor = $newFactor;
        return $this;
    }

    /**
     * Sets a name.
     *
     * @param  String $newName New list name.
     * @return AdmissionUserList
     */
    public function setName($newName)
    {
        $this->name = $newName;
        return $this;
    }

    /**
     * Sets a new owner.
     *
     * @param  String $newOwnerId New owner Id.
     * @return AdmissionUserList
     */
    public function setOwnerId($newOwnerId)
    {
        $this->ownerId = $newOwnerId;
        return $this;
    }

    /**
     * Sets a set of new list members, replacing previous entries.
     *
     * @param  Array $newUsers New member list.
     * @return AdmissionUserList
     */
    public function setUsers($newUsers)
    {
        $this->users = [];
        foreach ($newUsers as $userId) {
            $this->addUser($userId);
        }
        return $this;
    }

    public function describe(array $wrapper = ['', '']): string
    {
        if ($this->getFactor() == 0) {
            return _('Bei der Platzverteilung zu Veranstaltungen werden die '
                   . 'betreffenden Personen nur nachrangig berücksichtigt.');
        }

        if ($this->getFactor() == PHP_INT_MAX) {
            return _('Bei der Platzverteilung zu Veranstaltungen werden die '
                   . 'betreffenden Personen vor allen anderen einen Platz erhalten.');
        }

        return sprintf(
            _('Bei der Platzverteilung zu Veranstaltungen haben die betreffenden '
            . 'Personen gegenüber Anderen eine %s-fache Chance darauf, einen Platz zu '
            . 'erhalten.'),
            $wrapper[0] . $this->getFactor() . $wrapper[1]
        );
    }

    /**
     * Function for storing the data to DB. Is not called automatically on
     * changing object values.
     */
    public function store() {
        // Generate new ID if list doesn't exist in DB yet.
        if (!$this->id) {
            do {
                $newid = md5(uniqid('AdmissionUserList', true));
                $db = DBManager::get()->query("SELECT `list_id`
                    FROM `admissionfactor` WHERE `list_id`='.$newid.'");
            } while ($db->fetch());
            $this->id = $newid;
        }
        // Store basic list data.
        $stmt = DBManager::get()->prepare("INSERT INTO `admissionfactor`
            (`list_id`, `name`, `factor`, `owner_id`, `mkdate`, `chdate`)
            VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE
            `name`=VALUES(`name`), `factor`=VALUES(`factor`),
            `owner_id`=VALUES(`owner_id`), `chdate`=VALUES(`chdate`)");
        $stmt->execute([$this->id, $this->name, $this->factor,
            $this->ownerId, time(), time()]);
        // Clear all old user assignments to this list.
        DBManager::get()->exec("DELETE FROM `user_factorlist` WHERE `list_id`='".
            $this->id."' AND `user_id` NOT IN ('".
            implode("', '", array_keys($this->users))."')");
        // Store assigned users.
        foreach ($this->users as $userId => $assigned) {
            $stmt = DBManager::get()->prepare("INSERT INTO `user_factorlist`
                (`list_id`, `user_id`, `mkdate`)
                VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE
                `user_id`=VALUES(`user_id`)");
            $stmt->execute([$this->id, $userId, time()]);
        }
        return $this;
    }

    /**
     * String representation of this object.
     */
    public function toString()
    {
        $tpl = $GLOBALS['template_factory']->open('admission/userlist');
        $tpl->set_attribute('userlist', $this);
        return $tpl->render();
    }

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

}