forked from BoldGrid/w3-total-cache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExtension_CloudFlare_Api.php
370 lines (297 loc) · 8.54 KB
/
Extension_CloudFlare_Api.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
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
<?php
namespace W3TC;
/**
* CloudFlare API
*/
class Extension_CloudFlare_Api {
static private $_root_uri = 'https://api.cloudflare.com/client/v4';
private $_email;
private $_key;
private $_zone_id;
private $_timelimit_api_request;
function __construct( $config ) {
$this->_email = $config['email'];
$this->_key = $config['key'];
$this->_zone_id =
( isset( $config['zone_id'] ) ? $config['zone_id'] : '' );
if ( !isset( $config['timelimit_api_request'] ) ||
$config['timelimit_api_request'] < 1 )
$this->_timelimit_api_request = 30;
else
$this->_timelimit_api_request = $config['timelimit_api_request'];
}
/**
* Makes external event request
*
* @param string $type
* @param string $value
* @return array
*/
public function external_event( $type, $value ) {
$url = sprintf( 'https://www.cloudflare.com/ajax/external-event.html?' .
'u=%s&tkn=%s&evnt_t=%s&evnt_v=%s',
urlencode( $this->_email ), urlencode( $this->_key ),
urlencode( $type ), urlencode( $value ) );
$response = Util_Http::get( $url );
if ( !is_wp_error( $response ) ) {
return json_decode( $response['body'] );
}
return null;
}
/**
* Check
*
* @throws Util_WpFile_FilesystemOperationException
* @throws FileOperationException
*/
public function get_ip_ranges() {
$data = array();
$response = Util_Http::get( 'https://www.cloudflare.com/ips-v4' );
if ( !is_wp_error( $response ) ) {
$ip4_data = $response['body'];
$ip4_data = explode( "\n", $ip4_data );
$data['ip4'] = $ip4_data;
}
$response = Util_Http::get( 'https://www.cloudflare.com/ips-v6' );
if ( !is_wp_error( $response ) ) {
$ip6_data = $response['body'];
$ip6_data = explode( "\n", $ip6_data );
$data['ip6'] = $ip6_data;
}
return $data;
}
public function zones($page = 1) {
return $this->_wp_remote_request_with_meta( 'GET',
self::$_root_uri . '/zones?page=' . urlencode($page) );
}
public function zone($id) {
$a = $this->_wp_remote_request( 'GET',
self::$_root_uri . '/zones/' . $id );
return $a;
}
public function zone_settings() {
$a = $this->_wp_remote_request( 'GET',
self::$_root_uri . '/zones/' . $this->_zone_id . '/settings' );
$by_id = array();
foreach ( $a as $i ) {
$by_id[$i['id']] = $i;
}
return $by_id;
}
public function zone_setting_set( $name, $value ) {
return $this->_wp_remote_request( 'PATCH',
self::$_root_uri . '/zones/' . $this->_zone_id . '/settings/' . $name,
json_encode( array( 'value' => $value ) ) );
}
/**
* Prepares the analytics dashboard widget query to be performed via the CF GraphQL API
*
* @throws Exception
* @return array
*/
public function analytics_dashboard( $start, $end, $type = 'day' ) {
$dataset = 'httpRequests1dGroups';
$datetime_filter = 'date';
if($type === 'hour') {
$dataset = 'httpRequests1hGroups';
$datetime_filter = 'datetime';
}
return $this->_wp_remote_request_graphql( 'POST',
self::$_root_uri . '/graphql',
"{ \"query\": \"query {
viewer {
zones(filter: {zoneTag: \\\"" . $this->_zone_id . "\\\"}) {
" . $dataset . "(
orderBy: [" . $datetime_filter . "_ASC],
limit: 100,
filter: {
" . $datetime_filter . "_geq: \\\"" . $start . "\\\",
" . $datetime_filter . "_lt: \\\"" . $end . "\\\"
}
) {
dimensions {
" . $datetime_filter . "
}
sum {
bytes
cachedBytes
cachedRequests
pageViews
requests
threats
}
uniq {
uniques
}
}
}
}
}\"}"
);
}
public function purge() {
return $this->_wp_remote_request( 'DELETE',
self::$_root_uri . '/zones/' . $this->_zone_id . '/purge_cache',
'{"purge_everything":true}' );
}
/**
* Performs the CF API request
*
* @throws Exception
* @return array
*/
private function _wp_remote_request( $method, $url, $body = array() ) {
if ( empty( $this->_email ) || empty( $this->_key ) ) {
throw new \Exception('Not authenticated');
}
$headers = $this->_generate_wp_remote_request_headers();
$result = wp_remote_request( $url, array(
'method' => $method,
'headers' => $headers,
'timeout' => $this->_timelimit_api_request,
'body' => $body
) );
if ( is_wp_error( $result ) ) {
throw new \Exception( 'Failed to reach API endpoint' );
}
$response_json = @json_decode( $result['body'], true );
if ( is_null( $response_json ) || !isset( $response_json['success'] ) ) {
throw new \Exception(
'Failed to reach API endpoint, got unexpected response ' .
str_replace( '<', '.', str_replace( '>', '.', $result['body'] ) ) );
}
if ( !$response_json['success'] ) {
$errors = array();
if ( isset( $response_json['errors'] ) ) {
foreach ( $response_json['errors'] as $e ) {
if ( !empty( $e['message'] ) )
$errors[] = $e['message'];
}
}
if ( empty( $errors ) )
$errors[] = 'Request failed';
throw new \Exception( implode( ', ', $errors ) );
}
if ( isset( $response_json['result'] ) ) {
return $response_json['result'];
}
return array();
}
/**
* Performs the CF API request with meta
*
* @throws Exception
* @return array
*/
private function _wp_remote_request_with_meta( $method, $url, $body = array() ) {
if ( empty( $this->_email ) || empty( $this->_key ) ) {
throw new \Exception('Not authenticated');
}
$headers = $this->_generate_wp_remote_request_headers();
$result = wp_remote_request( $url, array(
'method' => $method,
'headers' => $headers,
'timeout' => $this->_timelimit_api_request,
'body' => $body
) );
if ( is_wp_error( $result ) )
throw new \Exception( 'Failed to reach API endpoint' );
$response_json = @json_decode( $result['body'], true );
if ( is_null( $response_json ) || !isset( $response_json['success'] ) ) {
throw new \Exception(
'Failed to reach API endpoint, got unexpected response ' .
$result['body'] );
}
if ( !$response_json['success'] ) {
$errors = array();
if ( isset( $response_json['errors'] ) ) {
foreach ( $response_json['errors'] as $e ) {
if ( !empty( $e['message'] ) )
$errors[] = $e['message'];
}
}
if ( empty( $errors ) )
$errors[] = 'Request failed';
throw new \Exception( implode( ', ', $errors ) );
}
if ( isset( $response_json['result'] ) ) {
return $response_json;
}
return array();
}
/**
* Performs the CF GraphQL API request
*
* @throws Exception
* @return array
*/
private function _wp_remote_request_graphql( $method, $url, $body ) {
if ( empty( $this->_email ) || empty( $this->_key ) ) {
throw new \Exception('Not authenticated');
}
$headers = $this->_generate_wp_remote_request_headers();
$body = preg_replace( '/\s\s+/', ' ', $body );
$result = wp_remote_request( $url, array(
'method' => $method,
'headers' => $headers,
'timeout' => $this->_timelimit_api_request,
'body' => $body
) );
if ( is_wp_error( $result ) ) {
throw new \Exception( 'Failed to reach API endpoint' );
}
$response_json = @json_decode( $result['body'], true );
if ( is_null( $response_json ) ) {
throw new \Exception(
'Failed to reach API endpoint, got unexpected response ' .
str_replace( '<', '.', str_replace( '>', '.', $result['body'] ) ) );
}
if ( isset( $response_json['errors'] ) ) {
$errors = array();
foreach ( $response_json['errors'] as $e ) {
if ( !empty( $e['message'] ) )
$errors[] = $e['message'];
}
if ( empty( $errors ) )
$errors[] = 'Request failed';
throw new \Exception( implode( ', ', $errors ) );
}
if ( isset( $response_json['data'] ) ) {
return $response_json['data'];
}
return array();
}
/**
* Generates the appropriate request headers for CF API requests based on token or global key presence
*
* @since 2.2.1
*
* @throws Exception
* @return array
*/
private function _generate_wp_remote_request_headers() {
if ( empty( $this->_email ) || empty( $this->_key ) ) {
throw new \Exception('Missing authentication email and/or API token / global key');
}
$headers = array();
// CF API Token
if( strlen( $this->_key ) == 40 ) {
$headers = array(
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $this->_key
);
}
// CF Legacy API Global Key
else if ( strlen( $this->_key ) == 37 ) {
$headers = array(
'Content-Type' => 'application/json',
'X-Auth-Key' => $this->_key,
'X-Auth-Email' => $this->_email
);
}
else {
throw new \Exception('Improper API token / global key length');
}
return $headers;
}
}