-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcron.php
More file actions
199 lines (168 loc) · 4.99 KB
/
cron.php
File metadata and controls
199 lines (168 loc) · 4.99 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
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
<?php
declare(strict_types=1);
const CACHE_TTL_SECONDS = 300; // 5 minutes
$configFile = __DIR__ . '/.env.php';
if (!file_exists($configFile)) {
fwrite(STDERR, sprintf('Config file missing: %s%s', $configFile, PHP_EOL));
exit(1);
}
$config = require $configFile;
if (!is_array($config)) {
fwrite(STDERR, sprintf('Config file must return an array: %s%s', $configFile, PHP_EOL));
exit(1);
}
$targets = $config['targets'] ?? null;
if (!is_array($targets) || $targets === []) {
fwrite(STDERR, sprintf('Config missing "targets" array: %s%s', $configFile, PHP_EOL));
exit(1);
}
foreach ($targets as $target) {
$file = $target['file'];
if (isCacheFresh($file)) {
continue;
}
$fetch = fetchJson($target['url']);
if (!$fetch['ok']) {
logError($target['name'], $fetch['message']);
continue;
}
if (!writeAtomically($file, $fetch['body'])) {
logError($target['name'], sprintf('failed to write cache file "%s"', $file));
continue;
}
}
/**
* Determine whether the existing cache file is still fresh.
*/
function isCacheFresh(string $path): bool
{
if (!file_exists($path)) {
return false;
}
$age = time() - (int) filemtime($path);
return $age < CACHE_TTL_SECONDS;
}
/**
* Fetch JSON from the remote endpoint and validate the response.
*
* @return array{ok:bool, body?:string, message:string|null}
*/
function fetchJson(string $url): array
{
$body = httpRequest($url, $statusCode, $err);
if ($body === null) {
return [
'ok' => false,
'message' => $err ?? 'unknown error',
];
}
if ($statusCode < 200 || $statusCode >= 300) {
return [
'ok' => false,
'message' => sprintf('unexpected HTTP status %d', $statusCode),
];
}
json_decode($body);
if (json_last_error() !== JSON_ERROR_NONE) {
return [
'ok' => false,
'message' => sprintf('invalid JSON payload: %s', json_last_error_msg()),
];
}
return [
'ok' => true,
'body' => $body,
'message' => null,
];
}
/**
* Perform an HTTP GET request and return the response body.
*
* @param int|null $status Status code returned by the request (if known)
* @param string|null $error Error message when the request fails
*/
function httpRequest(string $url, ?int &$status, ?string &$error): ?string
{
$error = null;
$status = null;
$ch = curl_init($url);
if ($ch === false) {
$error = 'unable to initialize cURL';
return null;
}
$headers = [
'Accept: application/json',
];
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_FAILONERROR => false,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_REFERER => 'https://reg.howloween.ca/',
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36',
]);
// $responseHeaders = [];
// curl_setopt($ch, CURLOPT_HEADERFUNCTION, function ($ch, string $header) use (&$responseHeaders) {
// $len = strlen($header);
// $normalized = trim($header);
// if ($normalized === '') {
// return $len;
// }
// $responseHeaders[] = $normalized;
// return $len;
// });
$body = curl_exec($ch);
// $info = curl_getinfo($ch);
// file_put_contents(
// __DIR__ . '/cron-debug.log',
// sprintf(
// "[%s]\nURL: %s\nStatus: %d\nResponse headers:\n%s\nBody (first 2 KB):\n%s\n\n",
// (new DateTimeImmutable())->format(DateTimeInterface::ATOM),
// $info['url'] ?? $url,
// $info['http_code'] ?? 0,
// implode("\n", $responseHeaders) ?: '(none)',
// $body //substr($body, 0, 2048)
// ),
// FILE_APPEND
// );
if ($body === false) {
$error = curl_error($ch) ?: 'curl_exec failed';
curl_close($ch);
return null;
}
$status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
return $body;
}
/**
* Write the supplied content to the target path atomically.
*/
function writeAtomically(string $path, string $content): bool
{
$dir = dirname($path);
$temp = tempnam($dir, 'tmp');
if ($temp === false) {
return false;
}
$bytes = file_put_contents($temp, $content, LOCK_EX);
if ($bytes === false) {
@unlink($temp);
return false;
}
if (!rename($temp, $path)) {
@unlink($temp);
return false;
}
return true;
}
/**
* Log an error message to STDERR for visibility in cron output.
*/
function logError(string $name, string $message): void
{
$timestamp = (new DateTimeImmutable())->format(DateTimeInterface::ATOM);
$line = sprintf('[%s] %s: %s', $timestamp, $name, $message);
fwrite(STDERR, $line . PHP_EOL);
}