-
Notifications
You must be signed in to change notification settings - Fork 2
/
ovingsspeilet.php
118 lines (105 loc) · 2.75 KB
/
ovingsspeilet.php
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
<?php
require('config.php');
date_default_timezone_set('Europe/Oslo');
function db() {
static $dbh;
if (!$dbh) {
try {
$dbh = new PDO(DB_DSN, DB_USER, DB_PASS);
if (substr(DB_DSN, 0, 6) === 'mysql:')
$dbh->query('SET GLOBAL SQL_MODE=ANSI_QUOTES');
} catch (PDOException $err) {
echo 'DB connection failed: ' . $err->getMessage();
exit();
}
}
return $dbh;
}
switch ($_SERVER['REQUEST_METHOD'] . ' ' . @$_GET['action']) {
default:
header('Content-Type: text/html; charset="utf-8"');
readfile('ovingsspeilet.html');
break;
case 'GET events':
header('Content-Type: application/json; charset="utf-8"');
$values =
[ date('Y-m-d H:i:s', strtotime($_GET['start']))
, date('Y-m-d H:i:s', strtotime($_GET['end']))
];
$sql = 'SELECT * FROM "ovingsspeilet" WHERE "start" >= ? AND "end" <= ?';
$sth = db()->prepare($sql);
$sth->execute($values);
echo '[';
$first = true;
while ($row = $sth->fetchObject()) {
$json =
[ 'id' => $row->id
, 'start' => $row->start
, 'end' => $row->end
, 'title' => $row->title
, 'details' => $row->details
, 'contact_name' => $row->contact_name
, 'contact_phone' => $row->contact_phone
];
if ($first) {
$first = false;
echo " ";
} else {
echo "\n, ";
}
echo json_encode($json);
}
echo "\n]";
break;
case 'POST delete':
header('Content-Type: text/plain; charset="utf-8"');
$sql = 'DELETE FROM "ovingsspeilet" WHERE "id" = ?';
$sth = db()->prepare($sql);
echo $sth->execute([ (int) $_POST['id'] ]);
break;
case 'POST save':
header('Content-Type: text/plain; charset="utf-8"');
$values =
[ DateTime::createFromFormat('Y-m-d\TH:i+', $_POST['start'])->format('Y-m-d H:i:s')
, DateTime::createFromFormat('Y-m-d\TH:i+', $_POST['end'])->format('Y-m-d H:i:s')
, filter_input(INPUT_POST, 'contact_name', FILTER_UNSAFE_RAW)
, filter_input(INPUT_POST, 'contact_phone', FILTER_UNSAFE_RAW)
, filter_input(INPUT_POST, 'title', FILTER_UNSAFE_RAW)
, filter_input(INPUT_POST, 'details', FILTER_UNSAFE_RAW)
];
$id = (int) $_POST['id'];
if ($id) {
$sql = '
UPDATE "ovingsspeilet"
SET "start" = ?
, "end" = ?
, "contact_name" = ?
, "contact_phone" = ?
, "title" = ?
, "details" = ?
WHERE "id" = ?
';
$values[] = $id;
} else {
$sql = '
INSERT INTO "ovingsspeilet"
( "start"
, "end"
, "contact_name"
, "contact_phone"
, "title"
, "details"
)
VALUES
(?, ?, ?, ?, ?, ?)
';
}
$sth = db()->prepare($sql);
if ($sth->execute($values)) {
if (!$id) {
$id = db()->lastInsertId('ovingsspeilet_id_seq');
}
echo $id;
}
break;
}