summaryrefslogtreecommitdiff
path: root/includes/pages/user_ical.php
blob: 2f3a7ccc881e889e95daf31b4764b0e7d38dde87 (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
<?php

use Engelsystem\Http\Exceptions\HttpForbidden;

/**
 * Controller for ical output of users own shifts or any user_shifts filter.
 */
function user_ical()
{
    $request = request();
    $user = auth()->apiUser('key');

    if (
        !$request->has('key')
        || !preg_match('/^[\da-f]{32}$/', $request->input('key'))
        || !$user
    ) {
        throw new HttpForbidden('Missing or invalid key', ['content-type' => 'text/text']);
    }

    if (!auth()->can('ical')) {
        throw new HttpForbidden('Not allowed', ['content-type' => 'text/text']);
    }

    $ical_shifts = load_ical_shifts();

    send_ical_from_shifts($ical_shifts);
}

/**
 * Renders an ical calendar from given shifts array.
 *
 * @param array $shifts Shift
 */
function send_ical_from_shifts($shifts)
{
    header('Content-Type: text/calendar; charset=utf-8');
    header('Content-Disposition: attachment; filename=shifts.ics');
    $output = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//-//" . config('app_name') . "//DE\r\nCALSCALE:GREGORIAN\r\n";
    foreach ($shifts as $shift) {
        $output .= make_ical_entry_from_shift($shift);
    }
    $output .= "END:VCALENDAR\r\n";
    $output = trim($output, "\x0A");
    header('Content-Length: ' . strlen($output));
    raw_output($output);
}

/**
 * Renders an ical vevent from given shift.
 *
 * @param array $shift
 * @return string
 */
function make_ical_entry_from_shift($shift)
{
    $output = "BEGIN:VEVENT\r\n";
    $output .= 'UID:' . md5($shift['start'] . $shift['end'] . $shift['name']) . "\r\n";
    $output .= 'SUMMARY:' . str_replace("\n", "\\n", $shift['name'])
        . ' (' . str_replace("\n", "\\n", $shift['title']) . ")\r\n";
    if (isset($shift['Comment'])) {
        $output .= 'DESCRIPTION:' . str_replace("\n", "\\n", $shift['Comment']) . "\r\n";
    }
    $output .= 'DTSTART;TZID=Europe/Berlin:' . date("Ymd\THis", $shift['start']) . "\r\n";
    $output .= 'DTEND;TZID=Europe/Berlin:' . date("Ymd\THis", $shift['end']) . "\r\n";
    $output .= 'LOCATION:' . $shift['Name'] . "\r\n";
    $output .= "END:VEVENT\r\n";
    return $output;
}