-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathindex.php
More file actions
87 lines (85 loc) · 3.71 KB
/
Copy pathindex.php
File metadata and controls
87 lines (85 loc) · 3.71 KB
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
<?php
use Kirby\Cms\App as Kirby;
use Kirby\Http\Remote;
use Kirby\Http\Response;
Kirby::plugin('floriankarsten/plausible', [
'areas' => [
'plausible' => function ($kirby) {
return [
'label' => 'Analytics',
'icon' => 'chart',
'disabled' => false,
'menu' => true,
'link' => 'plausible',
'views' => [
[
'pattern' => 'plausible',
'action' => function () use ($kirby) {
return [
'component' => 'k-plausible-view',
'title' => 'Analytics',
'props' => [
'sharedLink' => $kirby->option('floriankarsten.plausible.sharedLink')
],
];
}
]
]
];
}
],
'routes' => function ($kirby) {
return [
[
'pattern' => 'plausible/script.js',
'method' => 'GET',
'action' => function () use ($kirby) {
if (!$kirby->option('floriankarsten.plausible.proxy.enabled', false)) {
return new Response('Proxying is disabled.', 'text/plain', 500);
}
$scriptUrl = $kirby->option('floriankarsten.plausible.scriptUrl');
if (!$scriptUrl) {
return new Response('Plausible script URL not configured.', 'text/plain', 500);
}
$cacheMinutes = $kirby->option('floriankarsten.plausible.proxy.cache', 60 * 24); // default to 24 hours
$script = $kirby->cache('floriankarsten.plausible')->getOrSet('script', function () use ($scriptUrl) {
$response = Remote::get($scriptUrl);
if ($response->code() === 200) {
return $response->content();
}
return null;
}, $cacheMinutes);
return new Response($script, 'application/javascript', 200, [
'Cache-Control' => 'public, max-age=' . ($cacheMinutes * 60),
]);
}
],
[
'pattern' => 'plausible/event',
'method' => 'POST',
'action' => function () use ($kirby) {
if (!$kirby->option('floriankarsten.plausible.proxy.enabled', false)) {
return new Response('Proxying is disabled.', 'text/plain', 500);
}
$request = $kirby->request();
$visitor = $kirby->visitor();
$scriptHost = $kirby->option('floriankarsten.plausible.proxy.plausibleEndpoint', 'https://plausible.io');
$plausibleEndpoint = rtrim($scriptHost, '/') . '/api/event';
$response = Remote::request($plausibleEndpoint, [
'method' => 'POST',
'agent' => $visitor->userAgent(),
'headers' => [
'X-Forwarded-For' => $visitor->ip(),
'Content-Type' => 'text/plain',
],
'data' => $request->body()->contents(),
]);
return new Response($response->content(), 'application/json', $response->code());
}
],
];
},
'snippets' => [
'plausible' => __DIR__ . '/snippets/plausible.php'
]
]);