-
Notifications
You must be signed in to change notification settings - Fork 88
/
Copy pathCdnEngine_RackSpaceCloudFiles.php
467 lines (409 loc) · 12 KB
/
CdnEngine_RackSpaceCloudFiles.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
<?php
/**
* File: CdnEngine_RackSpaceCloudFiles.php
*
* @package W3TC
*/
namespace W3TC;
/**
* Class CdnEngine_RackSpaceCloudFiles
*
* Rackspace Cloud Files CDN engine
*
* phpcs:disable PSR2.Classes.PropertyDeclaration.Underscore
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
* phpcs:disable WordPress.PHP.NoSilencedErrors.Discouraged
* phpcs:disable WordPress.WP.AlternativeFunctions
*/
class CdnEngine_RackSpaceCloudFiles extends CdnEngine_Base {
/**
* Access state
*
* @var array
*/
private $_access_state;
/**
* Container
*
* @var object
*/
private $_container;
/**
* CDN RackSpace API CloudFiles object
*
* @var Cdn_RackSpace_Api_CloudFiles
*/
private $_api_files;
/**
* CDN RackSpace API CloudFilesCdn object
*
* @var Cdn_RackSpace_Api_CloudFilesCdn
*/
private $_api_cdn;
/**
* Callback function to handle the updated access state.
*
* This callback is invoked with a JSON-encoded string containing the new access state
* whenever authentication occurs and the access state is refreshed.
*
* @var callable
*/
private $_new_access_state_callback;
/**
* Initializes the CdnEngine_RackSpaceCloudFiles class with configuration.
*
* @param array $config Configuration options for the class.
*
* @return void
*/
public function __construct( $config = array() ) {
$config = array_merge(
array(
'user_name' => '',
'api_key' => '',
'region' => '',
'container' => '',
'cname' => array(),
'access_state' => '',
),
$config
);
$this->_container = $config['container'];
$this->_new_access_state_callback = $config['new_access_state_callback'];
// init access state.
$this->_access_state = @json_decode( $config['access_state'], true );
if ( ! is_array( $this->_access_state ) ) {
$this->_access_state = array();
}
$this->_access_state = array_merge(
array(
'access_token' => '',
'access_region_descriptor' => array(),
'host_http' => '',
'host_https' => '',
),
$this->_access_state
);
parent::__construct( $config );
$this->_create_api(
array( $this, '_on_new_access_requested_api_files' ),
array( $this, '_on_new_access_requested_api_cdn' )
);
}
/**
* Creates API instances for files and CDN.
*
* @param callable $new_access_required_callback_api_files Callback for file API access requests.
* @param callable $new_access_required_callback_api_cdn Callback for CDN API access requests.
*
* @return void
*/
private function _create_api( $new_access_required_callback_api_files, $new_access_required_callback_api_cdn ) {
$this->_api_files = new Cdn_RackSpace_Api_CloudFiles(
array(
'access_token' => $this->_access_state['access_token'],
'access_region_descriptor' => $this->_access_state['access_region_descriptor'],
'new_access_required' => $new_access_required_callback_api_files,
)
);
$this->_api_cdn = new Cdn_RackSpace_Api_CloudFilesCdn(
array(
'access_token' => $this->_access_state['access_token'],
'access_region_descriptor' => $this->_access_state['access_region_descriptor'],
'new_access_required' => $new_access_required_callback_api_cdn,
)
);
}
/**
* Handles new access requests for file API.
*
* @return Cdn_RackSpace_Api_CloudFiles Instance of the file API.
*/
public function _on_new_access_requested_api_files() {
$this->_on_new_access_requested();
return $this->_api_files;
}
/**
* Handles new access requests for CDN API.
*
* @return Cdn_RackSpace_Api_CloudFilesCdn Instance of the CDN API.
*/
public function _on_new_access_requested_api_cdn() {
$this->_on_new_access_requested();
return $this->_api_cdn;
}
/**
* Processes new access requests and updates the access state.
*
* @return void
*
* @throws \Exception If authentication fails or the region is not found.
*/
private function _on_new_access_requested() {
$r = Cdn_RackSpace_Api_Tokens::authenticate( $this->_config['user_name'], $this->_config['api_key'] );
if ( ! isset( $r['access_token'] ) || ! isset( $r['services'] ) ) {
throw new \Exception( \esc_html__( 'Authentication failed.', 'w3-total-cache' ) );
}
$r['regions'] = Cdn_RackSpace_Api_Tokens::cloudfiles_services_by_region( $r['services'] );
if ( ! isset( $r['regions'][ $this->_config['region'] ] ) ) {
throw new \Exception(
\esc_html(
sprintf(
// translators: 1: Region name.
\__( 'Region %1$s not found.', 'w3-total-cache' ),
$this->_config['region']
)
)
);
}
$this->_access_state['access_token'] = $r['access_token'];
$this->_access_state['access_region_descriptor'] = $r['regions'][ $this->_config['region'] ];
$this->_create_api(
array( $this, '_on_new_access_requested_second_time' ),
array( $this, '_on_new_access_requested_second_time' )
);
$c = $this->_api_cdn->container_get( $this->_config['container'] );
$this->_access_state['host_http'] = substr( $c['x-cdn-uri'], 7 );
$this->_access_state['host_https'] = substr( $c['x-cdn-ssl-uri'], 8 );
call_user_func( $this->_new_access_state_callback, wp_json_encode( $this->_access_state ) );
}
/**
* Handles repeated access requests in case of authentication failure.
*
* @return void
*
* @throws \Exception Always throws an exception for failed authentication.
*/
private function _on_new_access_requested_second_time() {
throw new \Exception( \esc_html__( 'Authentication failed.', 'w3-total-cache' ) );
}
/**
* Formats a URL for a given file path.
*
* @param string $path The file path to format.
*
* @return string|false The formatted URL, or false if the domain is not found.
*/
public function _format_url( $path ) {
$domain = $this->get_domain( $path );
if ( $domain ) {
$scheme = $this->_get_scheme();
// it does not support '+', requires '%2B'.
$path = str_replace( '+', '%2B', $path );
$url = sprintf( '%s://%s/%s', $scheme, $domain, $path );
return $url;
}
return false;
}
/**
* Uploads files to Rackspace Cloud Files.
*
* @param array $files Array of file descriptors for upload.
* @param array $results Reference to an array for storing results.
* @param bool $force_rewrite Whether to force overwriting existing files.
* @param int|null $timeout_time Optional timeout time in seconds.
*
* @return bool True on success, false on error.
*/
public function upload( $files, &$results, $force_rewrite = false, $timeout_time = null ) {
foreach ( $files as $file ) {
$local_path = $file['local_path'];
$remote_path = $file['remote_path'];
// process at least one item before timeout so that progress goes on.
if ( ! empty( $results ) && ! is_null( $timeout_time ) && time() > $timeout_time ) {
return 'timeout';
}
if ( ! file_exists( $local_path ) ) {
$results[] = $this->_get_result(
$local_path,
$remote_path,
W3TC_CDN_RESULT_ERROR,
'Source file not found.',
$file
);
continue;
}
$file_content = file_get_contents( $local_path );
$do_write = true;
// rewrite is optional, check md5.
if ( ! $force_rewrite ) {
$object_meta = null;
try {
$object_meta = $this->_api_files->object_get_meta_or_null( $this->_container, $remote_path );
} catch ( \Exception $exception ) {
$results[] = $this->_get_result(
$local_path,
$remote_path,
W3TC_CDN_RESULT_ERROR,
sprintf( 'Unable to check object (%s).', $exception->getMessage() ),
$file
);
$do_write = false;
}
if ( is_array( $object_meta ) && isset( $object_meta['etag'] ) ) {
$md5_actual = md5( $file_content );
if ( $md5_actual === $object_meta['etag'] ) {
$results[] = $this->_get_result(
$local_path,
$remote_path,
W3TC_CDN_RESULT_OK,
'Object up-to-date.',
$file
);
$do_write = false;
}
}
}
if ( $do_write ) {
try {
$this->_api_files->object_create(
array(
'container' => $this->_container,
'name' => $remote_path,
'content_type' => Util_Mime::get_mime_type( $local_path ),
'content' => $file_content,
)
);
$results[] = $this->_get_result(
$local_path,
$remote_path,
W3TC_CDN_RESULT_OK,
'OK',
$file
);
} catch ( \Exception $exception ) {
$results[] = $this->_get_result(
$local_path,
$remote_path,
W3TC_CDN_RESULT_ERROR,
sprintf( 'Unable to create object (%s).', $exception->getMessage() ),
$file
);
}
}
}
return ! $this->_is_error( $results );
}
/**
* Deletes files from Rackspace Cloud Files.
*
* @param array $files Array of file descriptors to delete.
* @param array $results Reference to an array for storing results.
*
* @return bool True on success, false on error.
*/
public function delete( $files, &$results ) {
foreach ( $files as $file ) {
$local_path = $file['local_path'];
$remote_path = $file['remote_path'];
try {
$this->_api_files->object_delete( $this->_container, $remote_path );
$results[] = $this->_get_result(
$local_path,
$remote_path,
W3TC_CDN_RESULT_OK,
'OK',
$file
);
} catch ( \Exception $exception ) {
$results[] = $this->_get_result(
$local_path,
$remote_path,
W3TC_CDN_RESULT_ERROR,
sprintf( 'Unable to delete object (%s).', $exception->getMessage() ),
$file
);
}
}
return ! $this->_is_error( $results );
}
/**
* Tests the connection to Rackspace Cloud Files.
*
* @param string $error Reference to store error messages, if any.
*
* @return bool True if the test succeeds, false otherwise.
*/
public function test( &$error ) {
$filename = 'test_rscf_' . md5( time() );
try {
$object = $this->_api_files->object_create(
array(
'container' => $this->_container,
'name' => $filename,
'content_type' => 'text/plain',
'content' => $filename,
)
);
} catch ( \Exception $exception ) {
$error = sprintf( 'Unable to write object (%s).', $exception->getMessage() );
return false;
}
$result = true;
try {
$r = wp_remote_get( 'http://' . $this->get_host_http() . '/' . $filename );
if ( $r['body'] !== $filename ) {
$error = 'Failed to retrieve object after storing.';
$result = false;
}
} catch ( \Exception $exception ) {
$error = sprintf( 'Unable to read object (%s).', $exception->getMessage() );
$result = false;
}
try {
$this->_api_files->object_delete( $this->_container, $filename );
} catch ( \Exception $exception ) {
$error = sprintf( 'Unable to delete object (%s).', $exception->getMessage() );
$result = false;
}
return $result;
}
/**
* Retrieves the list of available domains for the service.
*
* @return array List of domain names.
*/
public function get_domains() {
if ( Util_Environment::is_https() ) {
if ( ! empty( $this->_config['cname'] ) ) {
return (array) $this->_config['cname'];
}
return array( $this->get_host_https() );
} else {
if ( ! empty( $this->_config['cname'] ) ) {
return (array) $this->_config['cname'];
}
return array( $this->get_host_http() );
}
}
/**
* Retrieves the service descriptor including the domain used for accessing the CDN.
*
* @return string Descriptor of the service including domain used for accessing the CDN.
*/
public function get_via() {
return sprintf( 'Rackspace Cloud Files: %s', parent::get_via() );
}
/**
* Retrieves the HTTP host URL.
*
* @return string The HTTP host URL.
*/
public function get_host_http() {
if ( empty( $this->_access_state['host_http'] ) ) {
$this->_on_new_access_requested();
}
return $this->_access_state['host_http'];
}
/**
* Retrieves the HTTPS host URL.
*
* @return string The HTTPS host URL.
*/
public function get_host_https() {
if ( empty( $this->_access_state['host_https'] ) ) {
$this->_on_new_access_requested();
}
return $this->_access_state['host_https'];
}
}