This repository has been archived by the owner on Dec 5, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwp-google-storage-api.php
396 lines (335 loc) · 12.9 KB
/
wp-google-storage-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
<?php
/**
* WP Google Storage API
*
* @link https://cloud.google.com/storage/docs/json_api/
* @package WP-API-Libraries\WP-Google-Stroage-API
*/
/*
* Plugin Name: WP Google Storage API
* Plugin URI: https://github.com/wp-api-libraries/wp-google-storage-api
* Description: Perform API requests to Google Storage in WordPress.
* Author: WP API Libraries
* Version: 1.0.0
* Author URI: https://wp-api-libraries.com
* GitHub Plugin URI: https://github.com/wp-api-libraries/wp-google-storage-api
* GitHub Branch: master
*/
/* Exit if accessed directly. */
if ( ! defined( 'ABSPATH' ) ) {
exit; }
/* Check if class exists. */
if ( ! class_exists( 'GoogleStorageAPI' ) ) {
/**
* GoogleStorageAPI Class.
*/
class GoogleStorageAPI {
/**
* API Key.
*
* @var string
*/
protected static $api_token;
/**
* Google storage api Endpoint
*
* @var string
* @access protected
*/
protected $base_uri = 'https://storage.googleapis.com/storage/v1/';
/**
* Google storage upload api Endpoint
*
* @var string
*/
protected $upload_uri = 'https://storage.googleapis.com/upload/storage/v1/';
/**
* Route being called.
*
* @access protected
* @var string
*/
protected $route = '';
/**
* Is the api call an upload.
*
* @var boolean
*/
protected $is_upload = false;
/**
* Object upload mime type
*
* @var string
*/
protected $upload_type;
/**
* Class constructor.
*
* @param string $api_token Google API Key.
*/
public function __construct( $api_token ) {
static::$api_token = $api_token;
}
/**
* Prepares API request.
*
* @param string $route API route to make the call to.
* @param array $args Arguments to pass into the API call.
* @param array $method HTTP Method to use for request.
* @return self Returns an instance of itself so it can be chained to the fetch method.
*/
protected function build_request( $route, $args = array(), $method = 'GET' ) {
// Start building query.
$this->set_headers();
$this->args['method'] = $method;
$this->args['timeout'] = 300;
$this->route = $route;
// Generate query string for GET requests.
if ( 'GET' === $method ) {
$this->route = add_query_arg( array_filter( $args ), $this->route );
} elseif ( ! $this->is_upload && 'application/json' === $this->args['headers']['Content-Type'] ) {
$this->args['body'] = wp_json_encode( $args );
} else {
$this->args['body'] = $args;
}
return $this;
}
/**
* Fetch the request from the API.
*
* @access private
* @return array|WP_Error Request results or WP_Error on request failure.
*/
protected function fetch() {
// Choose correct uri.
$uri = ( $this->is_upload ) ? $this->upload_uri : $this->base_uri;
// Make the request.
$response = wp_remote_request( $uri . $this->route, $this->args );
// Retrieve Status code & body.
$code = wp_remote_retrieve_response_code( $response );
$body = json_decode( wp_remote_retrieve_body( $response ) );
$this->clear();
// Return WP_Error if request is not successful.
if ( ! $this->is_status_ok( $code ) ) {
// translators: Server response status code.
return new WP_Error( 'response-error', sprintf( __( 'Status: %d', 'wp-google-storage-api' ), $code ), $body );
}
return $body;
}
/**
* Set request headers.
*/
protected function set_headers() {
// Set request headers.
$this->args['headers'] = array(
'Content-Type' => ( $this->is_upload ) ? $this->upload_type : 'application/json',
'Authorization' => 'Bearer ' . static::$api_token,
);
}
/**
* Clear query data.
*/
protected function clear() {
$this->is_upload = false;
$this->args = array();
$this->query_args = array();
}
/**
* Check if HTTP status code is a success.
*
* @param int $code HTTP status code.
* @return boolean True if status is within valid range.
*/
protected function is_status_ok( $code ) {
return ( 200 <= $code && 300 > $code );
}
/**
* Get Bucket.
*
* @param string $bucket Bucket to retrieve.
* @param array $args Args to pass in to api call.
* @return [type] [description]
*/
public function get_bucket( string $bucket, $args = array() ) {
$bucket = rawurlencode( $bucket );
return $this->build_request( "b/$bucket", $args = array() )->fetch();
}
/**
* Get Object.
*
* @link https://cloud.google.com/storage/docs/json_api/v1/objects/get
*
* @param string $bucket Bucket Name.
* @param string $object Object Name.
* @param array $args https://cloud.google.com/storage/docs/json_api/v1/objects/get#parameters ( Setting 'alt' =>'media' as a query arg, retrieves object data ).
* @return JSON|OBJECT Returns JSON with object metadata or the object data if 'alt' is set to 'media'.
*/
public function get_object( string $bucket, string $object, $args = array( 'alt' => 'json' ) ) {
$bucket = rawurlencode( $bucket );
$object = rawurlencode( $object );
return $this->build_request( "b/$bucket/o/$object", $args )->fetch();
}
/**
* Insert Object (https://cloud.google.com/storage/docs/json_api/v1/objects/insert)
*
* @see https://cloud.google.com/storage/docs/uploading-objects#rest-upload-objects
*
* @param string $bucket Bucket Name.
* @param string $file_path File path of the file to upload.
* @param string $name File name. If null the name in the filepath will be used.
* @param string $upload_type The type of upload request (media|multipart|resumable) default=media.
* @return JSON JSON response.
*/
public function insert_object( string $bucket, string $file_path, string $name = null, string $upload_type = 'media' ) {
$this->is_upload = true;
$bucket = rawurlencode( $bucket );
// Set file name from filepath if null.
$name = ( is_null( $name ) ) ? wp_basename( $file_path ) : $name;
// Set mime type.
$this->upload_type = mime_content_type( $file_path );
$file = file_get_contents( $file_path );
$route = add_query_arg(
array(
'uploadType' => $upload_type,
'name' => $name,
),
"b/$bucket/o"
);
return $this->build_request( $route, $file, 'POST' )->fetch();
}
/**
* Delete Object.
*
* @param string $bucket Bucket Name.
* @param string $object Object Name.
* @param array $args https://cloud.google.com/storage/docs/json_api/v1/objects/delete.
* @return JSON JSON response.
*/
public function delete_object( string $bucket, string $object, $args = array() ) {
$bucket = rawurlencode( $bucket );
$object = rawurlencode( $object );
// Add additional query args to request.
$route = add_query_arg( $args, "b/$bucket/o/$object" );
return $this->build_request( $route, array(), 'DELETE' )->fetch();
}
/**
* Update Object.
*
* Updates entire object to to only what is specified in args.
*
* @param string $bucket Bucket Name.
* @param string $object Object Name.
* @param array $args https://cloud.google.com/storage/docs/json_api/v1/objects#resource i.e array( 'metadata' => array( "foo" => "bar" ) ).
* @return JSON JSON response.
*/
public function update_object( string $bucket, string $object, $args = array() ) {
$bucket = rawurlencode( $bucket );
$object = rawurlencode( $object );
return $this->build_request( "b/$bucket/o/$object", $args, 'PUT' )->fetch();
}
/**
* Patch Object.
*
* Only updates fields specified in args.
*
* @param string $bucket Bucket Name.
* @param string $object Object Name.
* @param array $args https://cloud.google.com/storage/docs/json_api/v1/objects#resource i.e array( 'metadata' => array( "foo" => "bar" ) ).
* @return JSON JSON response.
*/
public function patch_object( string $bucket, string $object, $args = array() ) {
$bucket = rawurlencode( $bucket );
$object = rawurlencode( $object );
return $this->build_request( "b/$bucket/o/$object", $args, 'PATCH' )->fetch();
}
/**
* Generate Signed URL's V4 method
*
* @param string $service_account_file JSON string of the service account file.
* @param string $bucket_name Name of the google storage bucket.
* @param string $object_name Object name aka the filepath.
* @param integer $expiration Expiration time in seconds.
* @param string $http_method HTTP method for signed URL.
* @return string|WP_Error
*/
public static function generate_signed_urlv4( $service_account_file, $bucket_name, $object_name, $expiration = 604800, $http_method = 'GET' ) {
// Max expiration time is 7 days.
if ( $expiration > 604800 ) {
return new WP_Error( 'invalid-expiration', 'Expiration Time can\'t be longer than 604800 seconds (7 days).' );
}
// Check if service account file is valid.
$service_account = self::is_json_valid( $service_account_file );
if ( is_wp_error( $service_account ) ) {
return $service_account;
}
$active_time = gmdate( 'Ymd\THis\Z' );
$escaped_object_name = rawurlencode( $object_name );
// Prepare Canonical Query String.
$resource_url = 'https://storage.googleapis.com/' . $bucket_name . '/' . $escaped_object_name;
$credential_scope = gmdate( 'Ymd' ) . '/auto/storage/goog4_request';
$canonical_args = array(
'X-Goog-Algorithm' => 'GOOG4-RSA-SHA256',
'X-Goog-Credential' => rawurlencode( $service_account->client_email . '/' . $credential_scope ),
'X-Goog-Date' => $active_time,
'X-Goog-Expires' => $expiration,
'X-Goog-SignedHeaders' => 'host',
);
$canonical_url = add_query_arg( array_filter( $canonical_args ), $resource_url );
// Prepare the string to sign.
$canonical_request = $http_method . "\n/" . $bucket_name . '/' . $escaped_object_name . "\n" . str_replace( $resource_url . '?', '', $canonical_url ) . "\nhost:storage.googleapis.com\n\nhost\nUNSIGNED-PAYLOAD";
$hashed_canonical_request = hash( 'sha256', $canonical_request );
$string_to_sign = "GOOG4-RSA-SHA256\n" . $active_time . "\n" . $credential_scope . "\n" . $hashed_canonical_request;
if ( openssl_sign( $string_to_sign, $signature, $service_account->private_key, OPENSSL_ALGO_SHA256 ) ) {
$signature = bin2hex( $signature );
return $canonical_url . '&X-Goog-Signature=' . $signature;
}
return new WP_Error( 'invalid-private-key', 'The URL could not be signed. Please check your private key in the service account' );
}
/**
* Generate Signed URL's V2 method
*
* @param string $service_account_file JSON string of the service account file.
* @param string $bucket_name Name of the google storage bucket.
* @param string $object_name Object name aka the filepath.
* @param integer $expiration Expiration time in seconds.
* @param string $http_method HTTP method for signed URL.
* @return string|WP_Error
*/
public static function generate_signed_urlv2( $service_account_file, $bucket_name, $object_name, $expiration = 604800, $http_method = 'GET' ) {
if ( $expiration > 604800 ) {
return new WP_Error( 'invalid-expiration', 'Expiration Time can\'t be longer than 604800 seconds (7 days).' );
}
$service_account = self::is_json_valid( $service_account_file );
if ( is_wp_error( $service_account ) ) {
return $service_account;
}
$expiry = time() + $expiration;
$escaped_object_name = rawurlencode( $object_name );
$access_id = rawurlencode( $service_account->client_email );
$policy_string = $http_method . "\n\n\n" . $expiry . "\n/" . $bucket_name . '/' . $escaped_object_name;
if ( openssl_sign( $policy_string, $signature, $service_account->private_key, OPENSSL_ALGO_SHA256 ) ) {
$signature = rawurlencode( base64_encode( $signature ) );
return 'https://storage.googleapis.com/' . $bucket_name . '/' . $escaped_object_name . '?GoogleAccessId=' . $access_id . '&Expires=' . $expiry . '&Signature=' . $signature;
}
return new WP_Error( 'invalid-private-key', 'The URL could not be signed. Please check your private key in the service account' );
}
/**
* Is Service account JSON valid.
*
* @param string $service_account_json Service account json string to be validated.
* @return Object|WP_Error
*/
private static function is_json_valid( $service_account_json ) {
$service_account = json_decode( $service_account_json );
if ( json_last_error() !== JSON_ERROR_NONE
|| ! array_key_exists( 'private_key', $service_account )
|| ! array_key_exists( 'client_email', $service_account )
|| ! array_key_exists( 'token_uri', $service_account )
|| ! array_key_exists( 'auth_uri', $service_account )
) {
return new WP_Error( 'invalid-service-account-json', __( 'Please verify that a valid service account json string is being used.', 'wp-google-auth-api' ) );
}
return $service_account;
}
}
}