-
Notifications
You must be signed in to change notification settings - Fork 88
/
Copy pathCdn_BunnyCdn_Api.php
566 lines (504 loc) · 15.7 KB
/
Cdn_BunnyCdn_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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
<?php
/**
* File: Cdn_BunnyCdn_Api.php
*
* @since 2.6.0
* @package W3TC
*/
namespace W3TC;
/**
* Class: Cdn_BunnyCdn_Api
*
* phpcs:disable WordPress.PHP.NoSilencedErrors.Discouraged
* phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter
*
* @since 2.6.0
*/
class Cdn_BunnyCdn_Api {
/**
* Account API Key.
*
* @since 2.6.0
*
* @var string
*/
private $account_api_key;
/**
* Storage API Key.
*
* @since 2.6.0
*
* @var string
*/
private $storage_api_key;
/**
* Stream API Key.
*
* @since 2.6.0
*
* @var string
*/
private $stream_api_key;
/**
* API type.
*
* One of: "account", "storage", "stream".
*
* @since 2.6.0
*
* @var string
*/
private $api_type;
/**
* Pull zone id.
*
* @since 2.6.0
*
* @var int
*/
private $pull_zone_id;
/**
* Default edge rules.
*
* @since 2.6.0
*
* @var array
*/
private static $default_edge_rules = array(
array(
'ActionType' => 15, // BypassPermaCache.
'TriggerMatchingType' => 0, // MatchAny.
'Enabled' => true,
'Triggers' => array(
array(
'Type' => 3, // UrlExtension.
'PatternMatchingType' => 0, // MatchAny.
'PatternMatches' => array( '.zip' ),
),
),
'Description' => 'Bypass PermaCache for ZIP files',
),
array(
'ActionType' => 3, // OverrideCacheTime.
'TriggerMatchingType' => 0, // MatchAny.
'ActionParameter1' => '0',
'ActionParameter2' => '',
'Enabled' => true,
'Triggers' => array(
array(
'Type' => 1, // RequestHeader.
'PatternMatchingType' => 0, // MatchAny.
'PatternMatches' => array(
'*wordpress_logged_in_*',
'*wordpress_sec_*',
),
'Parameter1' => 'Cookie',
),
),
'Description' => 'Override Cache Time if logged into WordPress',
),
array(
'ActionType' => 15, // BypassPermaCache.
'TriggerMatchingType' => 0, // MatchAny.
'Enabled' => true,
'Triggers' => array(
array(
'Type' => 1, // RequestHeader.
'PatternMatchingType' => 0, // MatchAny.
'PatternMatches' => array(
'*wordpress_logged_in_*',
'*wordpress_sec_*',
),
'Parameter1' => 'Cookie',
),
),
'Description' => 'Bypass PermaCache if logged into WordPress',
),
array(
'ActionType' => 16, // OverrideBrowserCacheTime.
'TriggerMatchingType' => 0, // MatchAny.
'ActionParameter1' => '0',
'Enabled' => true,
'Triggers' => array(
array(
'Type' => 1, // RequestHeader.
'PatternMatchingType' => 0, // MatchAny.
'PatternMatches' => array(
'*wordpress_logged_in_*',
'*wordpress_sec_*',
),
'Parameter1' => 'Cookie',
),
),
'Description' => 'Override Browser Cache Time if logged into WordPress',
),
);
/**
* Class constructor for initializing API keys and pull zone ID.
*
* @since 2.6.0
*
* @param array $config Configuration array containing API keys and pull zone ID.
*/
public function __construct( array $config ) {
$this->account_api_key = ! empty( $config['account_api_key'] ) ? $config['account_api_key'] : '';
$this->storage_api_key = ! empty( $config['storage_api_key'] ) ? $config['storage_api_key'] : '';
$this->stream_api_key = ! empty( $config['stream_api_key'] ) ? $config['stream_api_key'] : '';
$this->pull_zone_id = ! empty( $config['pull_zone_id'] ) ? $config['pull_zone_id'] : '';
}
/**
* Filters the timeout time.
*
* @since 2.6.0
*
* @param int $time The original timeout time.
*
* @return int The adjusted timeout time.
*/
public function filter_timeout_time( $time ) {
return 600;
}
/**
* Disables SSL verification for HTTPS requests.
*
* @since 2.6.0
*
* @param bool $verify Whether to enable SSL verification (defaults to false).
*
* @return bool False to disable SSL verification.
*/
public function https_ssl_verify( $verify = false ) {
return false;
}
/**
* Lists all pull zones.
*
* @since 2.6.0
*
* @link https://docs.bunny.net/reference/pullzonepublic_index
*
* @return array|WP_Error API response or error object.
*/
public function list_pull_zones() {
$this->api_type = 'account';
return $this->wp_remote_get( \esc_url( 'https://api.bunny.net/pullzone' ) );
}
/**
* Gets the details of a specific pull zone.
*
* @since 2.6.0
*
* @param int $id The pull zone ID.
*
* @link https://docs.bunny.net/reference/pullzonepublic_index2
*
* @return array|WP_Error API response or error object.
*/
public function get_pull_zone( $id ) {
$this->api_type = 'account';
return $this->wp_remote_get(
\esc_url( 'https://api.bunny.net/pullzone/id' . $id )
);
}
/**
* Adds a new pull zone.
*
* @since 2.6.0
*
* @param array $data Data for the new pull zone.
*
* @link https://docs.bunny.net/reference/pullzonepublic_add
*
* @return array|WP_Error API response or error object.
*
* @throws \Exception If the pull zone name is invalid.
*/
public function add_pull_zone( array $data ) {
$this->api_type = 'account';
if ( empty( $data['Name'] ) || ! \is_string( $data['Name'] ) ) { // A Name string is required, which is used for the CDN hostname.
throw new \Exception( \esc_html__( 'A pull zone name (string) is required.', 'w3-total-cache' ) );
}
if ( \preg_match( '[^\w\d-]', $data['Name'] ) ) { // Only letters, numbers, and dashes are allowed in the Name.
throw new \Exception( \esc_html__( 'A pull zone name (string) is required.', 'w3-total-cache' ) );
}
return $this->wp_remote_post(
'https://api.bunny.net/pullzone',
$data
);
}
/**
* Updates an existing pull zone.
*
* @since 2.6.0
*
* @param int $id The pull zone ID.
* @param array $data Data for updating the pull zone.
*
* @link https://docs.bunny.net/reference/pullzonepublic_updatepullzone
*
* @return array|WP_Error API response or error object.
*
* @throws \Exception If the pull zone ID is invalid.
*/
public function update_pull_zone( $id, array $data ) {
$this->api_type = 'account';
$id = empty( $this->pull_zone_id ) ? $id : $this->pull_zone_id;
if ( empty( $id ) || ! \is_int( $id ) ) {
throw new \Exception( \esc_html__( 'Invalid pull zone id.', 'w3-total-cache' ) );
}
return $this->wp_remote_post(
'https://api.bunny.net/pullzone/' . $id,
$data
);
}
/**
* Deletes a pull zone.
*
* @since 2.6.0
*
* @param int $id The pull zone ID.
*
* @link https://docs.bunny.net/reference/pullzonepublic_delete
*
* @return array|WP_Error API response or error object.
*
* @throws \Exception If the pull zone ID is invalid.
*/
public function delete_pull_zone( $id ) {
$this->api_type = 'account';
$id = empty( $this->pull_zone_id ) ? $id : $this->pull_zone_id;
if ( empty( $id ) || ! \is_int( $id ) ) {
throw new \Exception( \esc_html__( 'Invalid pull zone id.', 'w3-total-cache' ) );
}
return $this->wp_remote_post(
\esc_url( 'https://api.bunny.net/pullzone/' . $id ),
array(),
array( 'method' => 'DELETE' )
);
}
/**
* Adds a custom hostname to a pull zone.
*
* @since 2.6.0
*
* @param string $hostname The custom hostname to add.
* @param int|null $pull_zone_id The pull zone ID (optional).
*
* @link https://docs.bunny.net/reference/pullzonepublic_addhostname
*
* @return void
*
* @throws \Exception If the pull zone ID or hostname is invalid.
*/
public function add_custom_hostname( $hostname, $pull_zone_id = null ) {
$this->api_type = 'account';
$pull_zone_id = empty( $this->pull_zone_id ) ? $pull_zone_id : $this->pull_zone_id;
if ( empty( $pull_zone_id ) || ! \is_int( $pull_zone_id ) ) {
throw new \Exception( \esc_html__( 'Invalid pull zone id.', 'w3-total-cache' ) );
}
if ( empty( $hostname ) || ! \filter_var( $hostname, FILTER_VALIDATE_DOMAIN ) ) {
throw new \Exception( \esc_html__( 'Invalid hostname', 'w3-total-cache' ) . ' "' . \esc_html( $hostname ) . '".' );
}
$this->wp_remote_post(
\esc_url( 'https://api.bunny.net/pullzone/' . $pull_zone_id . '/addHostname' ),
array( 'Hostname' => $hostname )
);
}
/**
* Gets the default edge rules for the pull zone.
*
* @since 2.6.0
*
* @return array Default edge rules.
*/
public static function get_default_edge_rules() {
return self::$default_edge_rules;
}
/**
* Adds an edge rule to a pull zone.
*
* @since 2.6.0
*
* @param array $data Data for the edge rule.
* @param int|null $pull_zone_id The pull zone ID (optional).
*
* @return void
*
* @throws \Exception If any required parameters are missing or invalid.
*/
public function add_edge_rule( array $data, $pull_zone_id = null ) {
$this->api_type = 'account';
$pull_zone_id = empty( $this->pull_zone_id ) ? $pull_zone_id : $this->pull_zone_id;
if ( empty( $pull_zone_id ) || ! \is_int( $pull_zone_id ) ) {
throw new \Exception( \esc_html__( 'Invalid pull zone id.', 'w3-total-cache' ) );
}
if ( ! isset( $data['ActionType'] ) || ! \is_int( $data['ActionType'] ) || $data['ActionType'] < 0 ) {
throw new \Exception( \esc_html__( 'Invalid parameter "ActionType".', 'w3-total-cache' ) );
}
if ( ! isset( $data['TriggerMatchingType'] ) || ! \is_int( $data['TriggerMatchingType'] ) || $data['TriggerMatchingType'] < 0 ) {
throw new \Exception( \esc_html__( 'Invalid parameter "TriggerMatchingType".', 'w3-total-cache' ) );
}
if ( ! isset( $data['Enabled'] ) || ! \is_bool( $data['Enabled'] ) ) {
throw new \Exception( \esc_html__( 'Missing parameter "Enabled".', 'w3-total-cache' ) );
}
if ( empty( $data['Triggers'] ) ) {
throw new \Exception( \esc_html__( 'Missing parameter "Triggers".', 'w3-total-cache' ) );
}
$this->wp_remote_post(
\esc_url( 'https://api.bunny.net/pullzone/' . $pull_zone_id . '/edgerules/addOrUpdate' ),
$data
);
}
/**
* Purges the cache.
*
* @since 2.6.0
*
* @param array $data Data for the purge operation.
*
* @return array|WP_Error API response or error object.
*/
public function purge( array $data ) {
$this->api_type = 'account';
return $this->wp_remote_get(
\esc_url( 'https://api.bunny.net/purge' ),
$data
);
}
/**
* Purges the cache for a specific pull zone.
*
* @since 2.6.0
*
* @param int|null $pull_zone_id The pull zone ID (optional).
*
* @return void
*
* @throws \Exception If the pull zone ID is invalid.
*/
public function purge_pull_zone( $pull_zone_id = null ) {
$this->api_type = 'account';
$pull_zone_id = empty( $this->pull_zone_id ) ? $pull_zone_id : $this->pull_zone_id;
if ( empty( $pull_zone_id ) || ! \is_int( $pull_zone_id ) ) {
throw new \Exception( \esc_html__( 'Invalid pull zone id.', 'w3-total-cache' ) );
}
$this->wp_remote_post( \esc_url( 'https://api.bunny.net/pullzone/' . $pull_zone_id . '/purgeCache' ) );
}
/**
* Retrieves the appropriate API key based on the specified type.
*
* @since 2.6.0
*
* @param string|null $type The type of API key to retrieve ('account', 'storage', or 'stream').
*
* @return string The API key.
*
* @throws \Exception If the API key type is invalid or the key is empty.
*/
private function get_api_key( $type = null ) {
if ( empty( $type ) ) {
$type = $this->api_type;
}
if ( ! \in_array( $type, array( 'account', 'storage', 'stream' ), true ) ) {
throw new \Exception( \esc_html__( 'Invalid API type; must be one of "account", "storage", "stream".', 'w3-total-cache' ) );
}
if ( empty( $this->{$type . '_api_key'} ) ) {
throw new \Exception( \esc_html__( 'API key value is empty.', 'w3-total-cache' ) );
}
return $this->{$type . '_api_key'};
}
/**
* Decodes the API response.
*
* @since 2.6.0
*
* @param array|WP_Error $result The result returned from the API request.
*
* @return array The decoded response data.
*
* @throws \Exception If the response is not successful or fails to decode.
*/
private function decode_response( $result ) {
if ( \is_wp_error( $result ) ) {
throw new \Exception( \esc_html__( 'Failed to reach API endpoint', 'w3-total-cache' ) );
}
$response_body = @\json_decode( $result['body'], true );
// Throw an exception if the response code/status is not ok.
if ( ! \in_array( $result['response']['code'], array( 200, 201, 204 ), true ) ) {
$message = isset( $response_body['Message'] ) ? $response_body['Message'] : $result['body'];
throw new \Exception(
\esc_html( \__( 'Response code ', 'w3-total-cache' ) . $result['response']['code'] . ': ' . $message )
);
}
return \is_array( $response_body ) ? $response_body : array();
}
/**
* Sends a GET request to a specified URL with optional data parameters.
*
* This method sends a GET request using `wp_remote_get` to the specified URL, including optional query parameters.
* It also adds custom headers for API authentication and content type. Timeout and SSL verification filters
* are applied during the request process. The response is processed using `decode_response` method.
*
* @since 2.6.0
*
* @param string $url The URL to send the GET request to.
* @param array $data Optional. An associative array of data to send as query parameters. Default is an empty array.
*
* @return mixed The decoded response from the API request.
*/
private function wp_remote_get( $url, array $data = array() ) {
$api_key = $this->get_api_key();
\add_filter( 'http_request_timeout', array( $this, 'filter_timeout_time' ) );
\add_filter( 'https_ssl_verify', array( $this, 'https_ssl_verify' ) );
$result = \wp_remote_get(
$url . ( empty( $data ) ? '' : '?' . \http_build_query( $data ) ),
array(
'headers' => array(
'AccessKey' => $api_key,
'Accept' => 'application/json',
),
)
);
\remove_filter( 'https_ssl_verify', array( $this, 'https_ssl_verify' ) );
\remove_filter( 'http_request_timeout', array( $this, 'filter_timeout_time' ) );
return self::decode_response( $result );
}
/**
* Sends a POST request to a specified URL with optional data and additional arguments.
*
* This method sends a POST request using `wp_remote_post` to the specified URL, including optional data in the request body
* and additional arguments. Custom headers for API authentication, content type, and accept type are included in the request.
* Filters for request timeout and SSL verification are applied during the request process. The response is processed using
* `decode_response` method.
*
* @since 2.6.0
*
* @param string $url The URL to send the POST request to.
* @param array $data Optional. An associative array of data to send in the request body. Default is an empty array.
* @param array $args Optional. Additional arguments to customize the POST request, such as custom headers or settings. Default is an empty array.
*
* @return mixed The decoded response from the API request.
*/
private function wp_remote_post( $url, array $data = array(), array $args = array() ) {
$api_key = $this->get_api_key();
\add_filter( 'http_request_timeout', array( $this, 'filter_timeout_time' ) );
\add_filter( 'https_ssl_verify', array( $this, 'https_ssl_verify' ) );
$result = \wp_remote_post(
$url,
\array_merge(
array(
'headers' => array(
'AccessKey' => $api_key,
'Accept' => 'application/json',
'Content-Type' => 'application/json',
),
'body' => empty( $data ) ? null : \wp_json_encode( $data ),
),
$args
)
);
\remove_filter( 'https_ssl_verify', array( $this, 'https_ssl_verify' ) );
\remove_filter( 'http_request_timeout', array( $this, 'filter_timeout_time' ) );
return self::decode_response( $result );
}
}