/
class-keycdn.php
321 lines (276 loc) · 8.76 KB
/
class-keycdn.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
<?php
/**
* A catch-all helper function for flushing URLs from the KeyCDN cache. Determines if the items are URLs, cache tags, or the keyword 'all' to flush the entire cache.
* @param array $items List of items to group by URL or cache tags or the keyword 'all'
*/
function keycdn_flush( $items = array() ) {
// This function plays traffic cop for different types of flush requests.
if( is_string( $items ) ) {
$items = array( $items );
}
if( !$items ) {
return;
}
$items = array_map( 'trim', $items );
$tags = array();
$urls = array();
$flush_whole_cache = false;
foreach( $items as $item ) {
$lowercase_item = strtolower( $item );
if( substr( $lowercase_item, 0, 4 ) == 'http' || $lowercase_item[0] == '/' ) {
$urls[] = $item;
} else if( $lowercase_item == 'all' ) {
$flush_whole_cache = true;
} else {
$tags[] = $item;
}
}
if( $flush_whole_cache ) {
keycdn_flush_all();
return;
}
if( !empty( $tags ) ) {
keycdn_flush_tags( $tags );
}
if( !empty( $urls ) ) {
keycdn_flush_urls( $urls );
}
}
add_action( 'cdn_integration_flush_urls', 'keycdn_flush' );
/**
* Flushes the entire KeyCDN cache (zone purge)
*/
function keycdn_flush_all() {
$options = get_cdn_integration_options();
$api_secret = $options['keycdn-api-secret'];
$zone_id = $options['keycdn-zone-id'];
$zone_url = $options['keycdn-zone-url'];
if( !$api_secret || !$zone_id || !$zone_url ) {
throw new Exception( 'Invalid KeyCDN settings!' );
return;
}
$request_url = 'https://api.keycdn.com/zones/purge/' . $zone_id . '.json';
$args = array(
'method' => 'GET',
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( $api_secret . ':' ),
),
'body' => '',
'timeout' => 30,
);
$response = wp_remote_post( $request_url, $args );
if( is_wp_error( $response ) ) {
error_log( 'KeyCDN Flush ALL Error: ' . $response->get_error_message() );
}
$output = array(
'url' => $request_url,
'args' => $args,
'response' => $response,
);
return $output;
}
/**
* Flushes all URLs from the KeyCDN cache where the "Cache Tag" header contains one or more of the given $tags
* @param array $tags Cache tags that should be flushed
*/
function keycdn_flush_tags( $tags = array() ) {
if( !$tags ) {
throw new Exception( '$tags argument passed to keycdn_flush_tags() is FALSE!' );
return;
}
if( is_string( $tags ) ) {
$tags = array( $tags );
}
$options = get_cdn_integration_options();
$api_secret = $options['keycdn-api-secret'];
$zone_id = $options['keycdn-zone-id'];
$zone_url = $options['keycdn-zone-url'];
if( !$api_secret || !$zone_id || !$zone_url ) {
throw new Exception( 'Invalid KeyCDN settings!' );
return;
}
$payload= json_encode( array( 'tags' => $tags, ) );
$request_url = 'https://api.keycdn.com/zones/purgetag/' . $zone_id . '.json';
$args = array(
'method' => 'DELETE',
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( $api_secret . ':' ),
'Accept' => 'application/json',
'Content-Type' => 'application/json',
),
'body' => $payload,
);
$response = wp_remote_post( $request_url, $args );
if( is_wp_error( $response ) ) {
error_log( 'KeyCDN Cache Tag Flush Error: ' . $response->get_error_message() );
}
$output = array(
'url' => $request_url,
'args' => $args,
'response' => $response,
);
return $output;
}
/**
* Flushes a list of URLs from the KeyCDN cache
* @param array $urls List of URLs to be flushed
*/
function keycdn_flush_urls( $urls = array() ) {
if( !$urls ) {
return;
}
$options = get_cdn_integration_options();
$api_secret = $options['keycdn-api-secret'];
$zone_id = $options['keycdn-zone-id'];
$zone_url = $options['keycdn-zone-url'];
$public_protocol = $options['public-protocol'];
$public_domain = $options['public-domain'];
if( !$api_secret || !$zone_id || !$zone_url ) {
throw new Exception( 'Invalid KeyCDN settings!' );
return;
}
$public_url = $public_protocol . '://' . $public_domain;
if( !$public_domain ) {
$public_url = get_site_url();
}
foreach( $urls as $i => $url ) {
$urls[ $i ] = str_replace( $public_url, $zone_url, $url );
}
$payload = json_encode( array( 'urls' => $urls, ) );
$request_url = 'https://api.keycdn.com/zones/purgeurl/' . $zone_id . '.json';
$args = array(
'method' => 'DELETE',
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( $api_secret . ':' ),
'Accept' => 'application/json',
'Content-Type' => 'application/json',
),
'body' => $payload,
);
$response = wp_remote_post( $request_url, $args );
if( is_wp_error( $response ) ) {
error_log( 'KeyCDN URL Flush Error: ' . $response->get_error_message() );
}
$output = array(
'url' => $request_url,
'args' => $args,
'response' => $response,
);
return $output;
}
/**
* Helper conditional to determne if the request is coming from a KeyCDN edge server
* See https://www.keycdn.com/support/frequently-asked-questions/#request-header-edge-server
*/
function is_keycdn_request() {
return ( isset( $_SERVER['HTTP_X_PULL'] ) && $_SERVER['HTTP_X_PULL'] == 'KeyCDN' );
}
/**
* If the request is from KeyCDN then use output buffering so the page response can be cached
* @return bool Whether the request is from KeyCDN
*/
function keycdn_output_buffering() {
return is_keycdn_request();
}
add_filter( 'continue_cdn_integration_buffering', 'keycdn_output_buffering' );
/**
* Adds the "Cache Tag" header to the request based on what kind of page is being served. This enables the flushing of specific subsets of pages in one go.
*/
function add_keycdn_cache_tags() {
if( is_admin() ) {
return;
}
$cache_tags = array( 'html' );
if( is_home() ) {
$cache_tags[] = 'home';
}
if( is_archive() ) {
$cache_tags[] = 'archive';
}
if( is_singular() ) {
$post = get_post();
$cache_tags[] = 'singlular';
$cache_tags[] = 'single-' . $post->post_type;
}
$cache_tags = apply_filters( 'keycdn_cache_tags', $cache_tags );
if( !headers_sent() ) {
header( 'Cache-Tag: ' . implode( ' ', $cache_tags ) );
}
}
add_action( 'wp', 'add_keycdn_cache_tags' );
/**
* Modify the HTTP headers WordPress sends for a page request.
* Allows us to specify caching headers for KeyCDN.
* @param array $headers The headers we will modify
* @return array The modified headers
*/
function keycdn_filter_wp_headers( $headers = array() ) {
$old_cache_control_values = array();
$new_max_age_value = apply_filters( 'keycdn_max_age', 10 );
$new_max_age_value = intval( $new_max_age_value );
$new_s_max_age_value = apply_filters( 'keycdn_s_max_age', DAY_IN_SECONDS );
$new_s_max_age_value = intval( $new_s_max_age_value );
// Provide an opportunity to prevent adding Cache-Control headers
if( $new_max_age_value == -1 || $new_s_max_age_value == -1 ) {
return $headers;
}
if( isset( $headers['Cache-Control'] ) ) {
$old_cache_control = $headers['Cache-Control'];
$old_cache_control_values = explode( ',', $old_cache_control );
$old_cache_control_values = array_map( 'trim', $old_cache_control_values );
// If the response is supposed to not be cached then bail
if(
in_array( 'no-cache', $old_cache_control_values ) ||
in_array( 'max-age=0', $old_cache_control_values )
) {
return $headers;
}
foreach( $old_cache_control_values as $index => $val ) {
if(
stristr( $val, 'max-age' ) ||
stristr( $val, 's-maxage' ) ||
stristr( $val, 'public' )
) {
unset( $old_cache_control_values[ $index ] );
}
}
}
$old_cache_control_values[] = 'max-age=' . intval( $new_max_age_value );
$old_cache_control_values[] = 's-maxage=' . intval( $new_s_max_age_value );
$old_cache_control_values[] = 'public';
$headers['Cache-Control'] = implode( ', ', $old_cache_control_values );
return $headers;
}
add_filter( 'wp_headers', 'keycdn_filter_wp_headers' );
/**
* Compare paths of the request and determine if we need to redirect
* @param string $redirect_url Proposed URL to redirect to
* @param string $request_url The Requested URL
* @return string/bool The URL to redirect to or false if no redirect should occur
*/
function keycdn_maybe_do_canonical_redirect( $redirect_url = '', $request_url = '' ) {
if( !is_keycdn_request() ) {
return $redirect_url;
}
$parts = parse_url( $redirect_url );
$redirect_path = '';
if ( isset( $parts['path'] ) && ! empty( $parts['path'] ) ) {
$redirect_path .= $parts['path'];
}
if ( isset( $parts['query'] ) && ! empty( $parts['query'] ) ) {
$redirect_path .= '?' . $parts['query'];
}
$parts = parse_url( $request_url );
$request_path = '';
if ( isset( $parts['path'] ) && ! empty( $parts['path'] ) ) {
$request_path .= $parts['path'];
}
if ( isset( $parts['query'] ) && ! empty( $parts['query'] ) ) {
$request_path .= '?' . $parts['query'];
}
if ( $redirect_path == $request_path ) {
return false;
}
return $redirect_url;
}
add_filter( 'redirect_canonical', 'keycdn_maybe_do_canonical_redirect', 10, 2 );