summaryrefslogtreecommitdiff
path: root/includes/controller/users_controller.php
blob: ae297851f222d4d66d725716384d1bd0995b764f (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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
<?php

use Engelsystem\Database\DB;
use Engelsystem\ShiftCalendarRenderer;
use Engelsystem\ShiftsFilter;

/**
 * Route user actions.
 *
 * @return array
 */
function users_controller()
{
    global $user;
    $request = request();

    if (!isset($user)) {
        redirect(page_link_to(''));
    }

    $action = 'list';
    if ($request->has('action')) {
        $action = $request->input('action');
    }

    switch ($action) {
        case 'view':
            return user_controller();
        case 'delete':
            return user_delete_controller();
        case 'edit_vouchers':
            return user_edit_vouchers_controller();
        case 'list':
        default:
            return users_list_controller();
    }
}

/**
 * Delete a user, requires to enter own password for reasons.
 *
 * @return array
 */
function user_delete_controller()
{
    global $privileges, $user;
    $request = request();

    if ($request->has('user_id')) {
        $user_source = User($request->query->get('user_id'));
    } else {
        $user_source = $user;
    }

    if (!in_array('admin_user', $privileges)) {
        redirect(page_link_to(''));
    }

    // You cannot delete yourself
    if ($user['UID'] == $user_source['UID']) {
        error(_('You cannot delete yourself.'));
        redirect(user_link($user));
    }

    if ($request->has('submit')) {
        $valid = true;

        if (
        !(
            $request->has('password')
            && verify_password($request->postData('password'), $user['Passwort'], $user['UID'])
        )
        ) {
            $valid = false;
            error(_('Your password is incorrect.  Please try it again.'));
        }

        if ($valid) {
            User_delete($user_source['UID']);

            mail_user_delete($user_source);
            success(_('User deleted.'));
            engelsystem_log(sprintf('Deleted %s', User_Nick_render($user_source)));

            redirect(users_link());
        }
    }

    return [
        sprintf(_('Delete %s'), $user_source['Nick']),
        User_delete_view($user_source)
    ];
}

/**
 * @return string
 */
function users_link()
{
    return page_link_to('users');
}

/**
 * @param array $user
 * @return string
 */
function user_edit_link($user)
{
    return page_link_to('admin_user', ['user_id' => $user['UID']]);
}

/**
 * @param array $user
 * @return string
 */
function user_delete_link($user)
{
    return page_link_to('users', ['action' => 'delete', 'user_id' => $user['UID']]);
}

/**
 * @param array $user
 * @return string
 */
function user_link($user)
{
    return page_link_to('users', ['action' => 'view', 'user_id' => $user['UID']]);
}

/**
 * @return array
 */
function user_edit_vouchers_controller()
{
    global $privileges, $user;
    $request = request();

    if ($request->has('user_id')) {
        $user_source = User($request->input('user_id'));
    } else {
        $user_source = $user;
    }

    if (!in_array('admin_user', $privileges)) {
        redirect(page_link_to(''));
    }

    if ($request->has('submit')) {
        $valid = true;

        $vouchers = '';
        if (
            $request->has('vouchers')
            && test_request_int('vouchers')
            && trim($request->input('vouchers')) >= 0
        ) {
            $vouchers = trim($request->input('vouchers'));
        } else {
            $valid = false;
            error(_('Please enter a valid number of vouchers.'));
        }

        if ($valid) {
            $user_source['got_voucher'] = $vouchers;

            User_update($user_source);

            success(_('Saved the number of vouchers.'));
            engelsystem_log(User_Nick_render($user_source) . ': ' . sprintf('Got %s vouchers',
                    $user_source['got_voucher']));

            redirect(user_link($user_source));
        }
    }

    return [
        sprintf(_('%s\'s vouchers'), $user_source['Nick']),
        User_edit_vouchers_view($user_source)
    ];
}

/**
 * @return array
 */
function user_controller()
{
    global $privileges, $user;
    $request = request();

    $user_source = $user;
    if ($request->has('user_id')) {
        $user_source = User($request->input('user_id'));
        if ($user_source == null) {
            error(_('User not found.'));
            redirect(page_link_to('/'));
        }
    }

    $shifts = Shifts_by_user($user_source, in_array('user_shifts_admin', $privileges));
    foreach ($shifts as &$shift) {
        // TODO: Move queries to model
        $shift['needed_angeltypes'] = DB::select('
            SELECT DISTINCT `AngelTypes`.*
            FROM `ShiftEntry`
            JOIN `AngelTypes` ON `ShiftEntry`.`TID`=`AngelTypes`.`id`
            WHERE `ShiftEntry`.`SID` = ?
            ORDER BY `AngelTypes`.`name`
            ',
            [$shift['SID']]
        );
        foreach ($shift['needed_angeltypes'] as &$needed_angeltype) {
            $needed_angeltype['users'] = DB::select('
                  SELECT `ShiftEntry`.`freeloaded`, `User`.*
                  FROM `ShiftEntry`
                  JOIN `User` ON `ShiftEntry`.`UID`=`User`.`UID`
                  WHERE `ShiftEntry`.`SID` = ?
                  AND `ShiftEntry`.`TID` = ?
                ',
                [$shift['SID'], $needed_angeltype['id']]
            );
        }
    }
    
    if ($user_source['api_key'] == '') {
        User_reset_api_key($user_source, false);
    }

    return [
        $user_source['Nick'],
        User_view(
            $user_source,
            in_array('admin_user', $privileges),
            User_is_freeloader($user_source),
            User_angeltypes($user_source),
            User_groups($user_source),
            $shifts,
            $user['UID'] == $user_source['UID'],
            User_tshirt_score($user_source),
            in_array('admin_active', $privileges)
        )
    ];
}

/**
 * List all users.
 *
 * @return array
 */
function users_list_controller()
{
    global $privileges;
    $request = request();

    if (!in_array('admin_user', $privileges)) {
        redirect(page_link_to(''));
    }

    $order_by = 'Nick';
    if ($request->has('OrderBy') && in_array($request->input('OrderBy'), User_sortable_columns())) {
        $order_by = $request->input('OrderBy');
    }

    $users = Users($order_by);
    foreach ($users as &$user) {
        $user['freeloads'] = count(ShiftEntries_freeloaded_by_user($user));
    }

    return [
        _('All users'),
        Users_view(
            $users,
            $order_by,
            User_arrived_count(),
            User_active_count(),
            User_force_active_count(),
            ShiftEntries_freeloaded_count(),
            User_tshirts_count(),
            User_got_voucher_count()
        )
    ];
}

/**
 * Second step of password recovery: set a new password using the token link from email
 *
 * @return string
 */
function user_password_recovery_set_new_controller()
{
    $request = request();
    $user_source = User_by_password_recovery_token($request->input('token'));
    if ($user_source == null) {
        error(_('Token is not correct.'));
        redirect(page_link_to('login'));
    }

    if ($request->has('submit')) {
        $valid = true;

        if (
            $request->has('password')
            && strlen($request->postData('password')) >= config('min_password_length')
        ) {
            if ($request->postData('password') != $request->postData('password2')) {
                $valid = false;
                error(_('Your passwords don\'t match.'));
            }
        } else {
            $valid = false;
            error(_('Your password is to short (please use at least 6 characters).'));
        }

        if ($valid) {
            set_password($user_source['UID'], $request->postData('password'));
            success(_('Password saved.'));
            redirect(page_link_to('login'));
        }
    }

    return User_password_set_view();
}

/**
 * First step of password recovery: display a form that asks for your email and send email with recovery link
 *
 * @return string
 */
function user_password_recovery_start_controller()
{
    $request = request();
    if ($request->has('submit')) {
        $valid = true;

        if ($request->has('email') && strlen(strip_request_item('email')) > 0) {
            $email = strip_request_item('email');
            if (check_email($email)) {
                $user_source = User_by_email($email);
                if ($user_source == null) {
                    $valid = false;
                    error(_('E-mail address is not correct.'));
                }
            } else {
                $valid = false;
                error(_('E-mail address is not correct.'));
            }
        } else {
            $valid = false;
            error(_('Please enter your e-mail.'));
        }

        if ($valid) {
            $token = User_generate_password_recovery_token($user_source);
            engelsystem_email_to_user(
                $user_source,
                _('Password recovery'),
                sprintf(
                    _('Please visit %s to recover your password.'),
                    page_link_to('user_password_recovery', ['token' => $token])
                )
            );
            success(_('We sent an email containing your password recovery link.'));
            redirect(page_link_to('login'));
        }
    }

    return User_password_recovery_view();
}

/**
 * User password recovery in 2 steps.
 * (By email)
 *
 * @return string
 */
function user_password_recovery_controller()
{
    if (request()->has('token')) {
        return user_password_recovery_set_new_controller();
    }

    return user_password_recovery_start_controller();
}

/**
 * Menu title for password recovery.
 *
 * @return string
 */
function user_password_recovery_title()
{
    return _('Password recovery');
}

/**
 * Loads a user from param user_id.
 *
 * return array
 */
function load_user()
{
    $request = request();
    if (!$request->has('user_id')) {
        redirect(page_link_to());
    }

    $user = User($request->input('user_id'));

    if ($user == null) {
        error(_('User doesn\'t exist.'));
        redirect(page_link_to());
    }

    return $user;
}

/**
 * @param ShiftsFilter $shiftsFilter
 * @return ShiftCalendarRenderer
 */
function shiftCalendarRendererByShiftFilter(ShiftsFilter $shiftsFilter)
{
    $shifts = Shifts_by_ShiftsFilter($shiftsFilter);
    $needed_angeltypes_source = NeededAngeltypes_by_ShiftsFilter($shiftsFilter);
    $shift_entries_source = ShiftEntries_by_ShiftsFilter($shiftsFilter);

    $needed_angeltypes = [];
    $shift_entries = [];
    foreach ($shifts as $shift) {
        $needed_angeltypes[$shift['SID']] = [];
        $shift_entries[$shift['SID']] = [];
    }
    foreach ($shift_entries_source as $shift_entry) {
        if (isset($shift_entries[$shift_entry['SID']])) {
            $shift_entries[$shift_entry['SID']][] = $shift_entry;
        }
    }
    foreach ($needed_angeltypes_source as $needed_angeltype) {
        if (isset($needed_angeltypes[$needed_angeltype['SID']])) {
            $needed_angeltypes[$needed_angeltype['SID']][] = $needed_angeltype;
        }
    }
    unset($needed_angeltypes_source);
    unset($shift_entries_source);

    if (
        in_array(ShiftsFilter::FILLED_FREE, $shiftsFilter->getFilled())
        && in_array(ShiftsFilter::FILLED_FILLED, $shiftsFilter->getFilled())
    ) {
        return new ShiftCalendarRenderer($shifts, $needed_angeltypes, $shift_entries, $shiftsFilter);
    }

    $filtered_shifts = [];
    foreach ($shifts as $shift) {
        $needed_angels_count = 0;
        $taken = 0;
        foreach ($needed_angeltypes[$shift['SID']] as $needed_angeltype) {
            $taken = 0;
            foreach ($shift_entries[$shift['SID']] as $shift_entry) {
                if ($needed_angeltype['angel_type_id'] == $shift_entry['TID'] && $shift_entry['freeloaded'] == 0) {
                    $taken++;
                }
            }

            $needed_angels_count += max(0, $needed_angeltype['count'] - $taken);
        }
        if (in_array(ShiftsFilter::FILLED_FREE, $shiftsFilter->getFilled()) && $taken < $needed_angels_count) {
            $filtered_shifts[] = $shift;
        }
        if (
            in_array(ShiftsFilter::FILLED_FILLED, $shiftsFilter->getFilled())
            && $taken >= $needed_angels_count
        ) {
            $filtered_shifts[] = $shift;
        }
    }

    return new ShiftCalendarRenderer($filtered_shifts, $needed_angeltypes, $shift_entries, $shiftsFilter);
}