-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.php
More file actions
264 lines (222 loc) · 9.89 KB
/
plugin.php
File metadata and controls
264 lines (222 loc) · 9.89 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
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
<?php
declare(strict_types=1);
/**
* Ava for Cloudflare® Plugin
*
* Automatically purge Cloudflare cache when content is rebuilt.
*
* Features:
* - Automatic cache purge on content rebuild
* - CLI commands for manual purge and status check
*
* Configuration in ava.php:
*
* 'cloudflare' => [
* 'enabled' => true,
* 'zone_id' => 'your-zone-id',
* 'api_token' => 'your-api-token', // Requires cache_purge:edit permission
* ],
*
* Cloudflare® is a registered trademark of Cloudflare, Inc.
* This plugin is not affiliated with or endorsed by Cloudflare, Inc.
*
* @package Ava\Plugins\Cloudflare
*/
use Ava\Application;
use Ava\Plugins\Hooks;
return [
'name' => 'Ava for Cloudflare®',
'version' => '1.1.0',
'description' => 'Automatically purge Cloudflare cache on content rebuild',
'author' => 'Ava CMS',
'boot' => function (Application $app) {
// Load configuration
$config = array_merge([
'enabled' => false,
'zone_id' => '',
'api_token' => '',
], $app->config('cloudflare', []));
// Skip if not enabled or missing required config
if (!$config['enabled']) {
return;
}
$isConfigured = !empty($config['zone_id']) && !empty($config['api_token']);
/**
* Purge entire Cloudflare cache zone.
*
* @return array{success: bool, message: string, details?: array}
*/
$purgeCache = function () use ($config): array {
if (empty($config['zone_id']) || empty($config['api_token'])) {
return [
'success' => false,
'message' => 'Cloudflare zone_id and api_token are required',
];
}
$url = "https://api.cloudflare.com/client/v4/zones/{$config['zone_id']}/purge_cache";
$payload = json_encode(['purge_everything' => true]);
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $payload,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . $config['api_token'],
'Content-Type: application/json',
],
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);
if ($curlError) {
return [
'success' => false,
'message' => 'cURL error: ' . $curlError,
];
}
$data = json_decode($response, true);
if ($httpCode === 200 && ($data['success'] ?? false)) {
return [
'success' => true,
'message' => 'Cloudflare cache purged successfully',
'details' => $data,
];
}
// Extract error message from Cloudflare response
$errors = $data['errors'] ?? [];
$errorMessage = !empty($errors)
? implode(', ', array_map(fn($e) => $e['message'] ?? 'Unknown error', $errors))
: 'Unknown error (HTTP ' . $httpCode . ')';
return [
'success' => false,
'message' => 'Cloudflare API error: ' . $errorMessage,
'details' => $data,
];
};
// Hook into content rebuild to automatically purge cache
if ($isConfigured) {
Hooks::addAction('indexer.rebuild', function () use ($purgeCache, $app) {
$result = $purgeCache();
// Log the result
$storagePath = $app->configPath('storage');
$logFile = $storagePath . '/logs/cloudflare.log';
$logEntry = sprintf(
"[%s] %s: %s\n",
date('Y-m-d H:i:s'),
$result['success'] ? 'SUCCESS' : 'ERROR',
$result['message']
);
// Ensure logs directory exists
$logsDir = dirname($logFile);
if (!is_dir($logsDir)) {
mkdir($logsDir, 0755, true);
}
file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
});
}
},
/*
|───────────────────────────────────────────────────────────────────────────
| CLI COMMANDS
|───────────────────────────────────────────────────────────────────────────
*/
'commands' => [
[
'name' => 'cloudflare:status',
'description' => 'Show Cloudflare integration status',
'handler' => function (array $args, $output, Application $app) {
$config = array_merge([
'enabled' => false,
'zone_id' => '',
'api_token' => '',
], $app->config('cloudflare', []));
$output->header('Cloudflare Integration Status');
$output->writeln('');
// Status table
$rows = [
['Enabled', $config['enabled'] ? 'Yes' : 'No'],
['Zone ID', !empty($config['zone_id']) ? substr($config['zone_id'], 0, 8) . '...' : '(not set)'],
['API Token', !empty($config['api_token']) ? '••••' . substr($config['api_token'], -4) : '(not set)'],
];
$output->table(['Setting', 'Value'], $rows);
$isConfigured = $config['enabled'] && !empty($config['zone_id']) && !empty($config['api_token']);
$output->writeln('');
if ($isConfigured) {
$output->success('✓ Cloudflare integration is active. Cache will be purged on rebuild.');
} else {
$output->warning('⚠ Cloudflare integration is not fully configured.');
$output->writeln('');
$output->info('Add to app/config/ava.php:');
$output->writeln('');
$output->writeln(" 'cloudflare' => [");
$output->writeln(" 'enabled' => true,");
$output->writeln(" 'zone_id' => 'your-zone-id',");
$output->writeln(" 'api_token' => 'your-api-token',");
$output->writeln(" ],");
}
return 0;
},
],
[
'name' => 'cloudflare:purge',
'description' => 'Purge all Cloudflare cached content',
'handler' => function (array $args, $output, Application $app) {
$config = array_merge([
'enabled' => false,
'zone_id' => '',
'api_token' => '',
], $app->config('cloudflare', []));
$output->header('Cloudflare Cache Purge');
$output->writeln('');
if (!$config['enabled']) {
$output->error('Cloudflare integration is not enabled.');
$output->info("Set 'cloudflare.enabled' => true in ava.php");
return 1;
}
if (empty($config['zone_id']) || empty($config['api_token'])) {
$output->error('Cloudflare zone_id and api_token are required.');
$output->info('Run ./ava cloudflare:status for configuration help.');
return 1;
}
$output->info('Purging Cloudflare cache...');
// Make API request
$url = "https://api.cloudflare.com/client/v4/zones/{$config['zone_id']}/purge_cache";
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode(['purge_everything' => true]),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . $config['api_token'],
'Content-Type: application/json',
],
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);
if ($curlError) {
$output->error('cURL error: ' . $curlError);
return 1;
}
$data = json_decode($response, true);
if ($httpCode === 200 && ($data['success'] ?? false)) {
$output->success('✓ Cloudflare cache purged successfully');
return 0;
}
// Extract error message
$errors = $data['errors'] ?? [];
$errorMessage = !empty($errors)
? implode(', ', array_map(fn($e) => $e['message'] ?? 'Unknown error', $errors))
: 'Unknown error (HTTP ' . $httpCode . ')';
$output->error('Cloudflare API error: ' . $errorMessage);
return 1;
},
],
],
];