PluginProbe
Media Cloud Sync / 1.1.1
Media Cloud Sync v1.1.1
1.4.0 1.3.12 1.3.11 1.3.10 trunk 1.0.0 1.0.1 1.0.2 1.0.3 1.1.0 1.1.1 1.2.0 1.2.10 1.2.11 1.2.12 1.2.13 1.2.2 1.2.3 1.2.4 1.2.5 1.2.6 1.2.7 1.2.8 1.2.9 1.3.0 All 34 releases
media-cloud-sync / includes / base / services / gcloud.php

gcloud.php in Media Cloud Sync 1.1.1, at includes/base/services/gcloud.php

553 lines 20.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 namespace Dudlewebs\WPMCS;
3
4 defined('ABSPATH') || exit;
5
6 // Libraries
7 use Dudlewebs\WPMCS\Google\Cloud\Storage\StorageClient;
8
9 use Exception;
10
11 class GCloud {
12 private $assets_url;
13 private $version;
14 private $token;
15
16 protected $config;
17 protected $bucketConfig;
18 protected $settings;
19 protected $credentials;
20 protected $bucket_name;
21 protected $bucket; // Object
22
23 public $service = 'gcloud';
24 public $gcloudClient = false;
25
26 /**
27 * Admin constructor.
28 * @since 1.0.0
29 */
30 public function __construct() {
31 $this->assets_url = WPMCS_ASSETS_URL;
32 $this->version = WPMCS_VERSION;
33 $this->token = WPMCS_TOKEN;
34
35 // Initialize setup
36 $this->init();
37 }
38
39 /**
40 * Initialise Client
41 */
42 public function init() {
43 $this->settings = Utils::get_settings();
44 $this->credentials = Utils::get_credentials();
45 $this->config = isset($this->credentials['config']) && !empty($this->credentials['config'])
46 ? $this->credentials['config']
47 : [];
48 $this->bucketConfig = isset($this->credentials['bucketConfig']) && !empty($this->credentials['bucketConfig'])
49 ? $this->credentials['bucketConfig']
50 : [];
51 $this->bucket_name = isset($this->bucketConfig['bucket_name']) && !empty($this->bucketConfig['bucket_name'])
52 ? $this->bucketConfig['bucket_name']
53 : '';
54
55 if (
56 isset($this->config['config_json']) && !empty($this->config['config_json']) &&
57 isset($this->config['config_json']['path']) && !empty($this->config['config_json']['path']) &&
58 isset($this->bucket_name) && !empty($this->bucket_name)
59 ) {
60 if(file_exists($this->config['config_json']['path'])){
61 // Set google client
62 $this->gcloudClient = new StorageClient([
63 'keyFilePath' => $this->config['config_json']['path'],
64 ]);
65 // Set bucket object
66 $this->bucket = $this->gcloudClient->bucket($this->bucket_name);
67 } else {
68 add_action('admin_notices', function (){
69 echo wp_kses_post(sprintf( "<div class='error'><p><strong>%s: </strong><br>Google Cloud Storage configuration file missing from the directory.
70 It may break the media url's as well as media uploads.<br>
71 <a href='%s'>Re-configure</a> plugin to fix the issue.
72 </p></div>",
73 esc_html__('Media Cloud Sync', 'media-cloud-sync'),
74 admin_url('admin.php?page='.$this->token . '-admin-ui#/configure')
75 ));
76 });
77 }
78 }
79 }
80
81 /**
82 * Verify Credentials
83 * @since 1.0.0
84 * @return boolean
85 */
86 public function verifyCredentials( $config_file ){
87 if (
88 isset($config_file) && !empty($config_file) &&
89 isset($config_file['path']) && !empty($config_file['path']) &&
90 file_exists($config_file['path'])
91 ) {
92 try {
93 $googleClient = new StorageClient([
94 'keyFilePath' => $config_file['path'],
95 ]);
96
97
98 //Listing all google Buckets
99 $buckets = $googleClient->buckets();
100
101 $newBucketFormat = [];
102 if(isset($buckets) && !empty($buckets)){
103 foreach($buckets as $bucket) {
104 $name = $bucket->name();
105 if(!empty($name)) {
106 // Fetch the bucket's metadata
107 $bucketInfo = $bucket->info();
108 $newBucketFormat[] = ['Name' => $name, 'CreationDate' => $bucketInfo['timeCreated']];
109 }
110 }
111 }
112
113 return array( 'message' => esc_html__('Credentials are valid', 'media-cloud-sync'), 'buckets' => $newBucketFormat, 'code' => 200, 'success' => true);
114 } catch (Exception $ex) {
115 return array('message' => $ex->getMessage() ?? esc_html__('Please check the authorization details', 'media-cloud-sync'), 'code' => 200, 'success' => false);
116 } catch (Exception $ex) {
117 return array('message' => $ex->getMessage() ?? esc_html__('Please check the authorization details', 'media-cloud-sync'), 'code' => 200, 'success' => false);
118 }
119 }
120 return array('message' => esc_html__('Insufficient Data. Please try again', 'media-cloud-sync'), 'code' => 200, 'success' => false);
121 }
122
123
124 /**
125 * Verify Bucket
126 * @since 1.0.0
127 * @return boolean
128 */
129 public function verifyBucket( $config_file, $bucket_name ){
130 if ( !( isset($config_file['path']) && !empty($config_file['path']) && file_exists($config_file['path']) && !empty($bucket_name) ) ) {
131 return ['message' => esc_html__('Insufficient Data. Please try again', 'media-cloud-sync'), 'code' => 200, 'success' => false];
132 }
133
134 try {
135 $googleClient = new StorageClient([
136 'keyFilePath' => $config_file['path'],
137 ]);
138
139 $bucket = $googleClient->bucket($bucket_name);
140 if ($bucket->exists()) {
141 $bucket_found = true;
142 } else {
143 return ['message' => esc_html__('No Buckets found', 'media-cloud-sync'), 'code' => 200, 'success' => false];
144 }
145 if ($bucket_found) {
146 $upload_dir = wp_upload_dir();
147 $file_dir = $upload_dir['basedir'] . '/' . Schema::getConstant('UPLOADS') . '/';
148
149 if (!is_dir($file_dir)) {
150 do_action( $this->token.'_create_plugin_dir' );
151 }
152
153 $fileName = $this->token."_verify.txt";
154 $localFileName = $file_dir.$this->token."-local-verify.txt";
155
156 $verify_file = fopen($file_dir.$fileName, "w");
157 $txt = "We are verifying input/output operations in Google Cloud\n";
158 fwrite($verify_file, $txt);
159 fclose($verify_file);
160
161 $upload = $bucket->upload(
162 fopen($file_dir . $fileName, 'r'),
163 [
164 'name' => $fileName,
165 'predefinedAcl' => 'publicRead',
166 ]
167 );
168
169 @unlink($file_dir . $fileName);
170
171 $object = $bucket->object($fileName);
172 if ($object->exists()) {
173 $object->downloadToFile($localFileName);
174 if (file_exists($localFileName)) {
175 @unlink($localFileName);
176 $object->delete();
177
178 if (!$object->exists()) {
179 return array('message' => esc_html__('Configuration for Google Cloud Storage verified successfully', 'media-cloud-sync'), 'code' => 200, 'success' => true);
180 } else {
181 return array('message' => esc_html__('Bucket has permission issues on deleting the object from bucket, Please check permission as well as policies', 'media-cloud-sync'), 'code' => 200, 'success' => false);
182 }
183 } else {
184 return array('message' => esc_html__('Bucket has permission issues on getting the object from bucket, Please check permission as well as policies', 'media-cloud-sync'), 'code' => 200, 'success' => false);
185 }
186 } else {
187 return array('message' => esc_html__('Bucket has permission issues on putting object in to bucket, Please check permission as well as policies', 'media-cloud-sync'), 'code' => 200, 'success' => false);
188 }
189 } else {
190 return ['message' => esc_html__('Bucket Name is incorrect', 'media-cloud-sync'), 'code' => 200, 'success' => false];
191 }
192 } catch (Exception $ex) {
193 return ['message' => $e->getMessage(), 'code' => 200, 'success' => false];
194 } catch (Exception $ex) {
195 return ['message' => $e->getMessage() ?? esc_html__('Please check the authorization details', 'media-cloud-sync'), 'code' => 200, 'success' => false];
196 } catch (Exception $ex) {
197 return ['message' => $ex->getMessage() ?? esc_html__('Please check the authorization details', 'media-cloud-sync'), 'code' => 200, 'success' => false];
198 }
199 }
200
201
202 /**
203 * Create Bucket
204 * @since 1.0.0
205 * @return boolean
206 */
207 public function createBucket( $config_file, $region, $bucket_name ){
208 if ( !( isset($config_file['path']) && !empty($config_file['path']) && file_exists($config_file['path']) && !empty($region) && !empty($bucket_name) ) ) {
209 return ['message' => esc_html__('Insufficient Data. Please try again', 'media-cloud-sync'), 'code' => 200, 'success' => false];
210 }
211
212 try {
213 $googleClient = new StorageClient([
214 'keyFilePath' => $config_file['path'],
215 ]);
216
217 // Create Bucket
218 $googleClient->createBucket($bucket_name, [
219 'location' => $region,
220 ]);
221
222 return [
223 'message' => esc_html__('Bucket created successfully. Choose bucket from list to select the bucket.', 'media-cloud-sync'),
224 'data' => [
225 'Name' => $bucket_name,
226 'CreationDate' => date('Y-m-d\TH:i:s\Z'),
227 ],
228 'code' => 200,
229 'success' => true,
230 ];
231
232 } catch (Exception $ex) {
233 return ['message' => $e->getMessage(), 'code' => 200, 'success' => false];
234 } catch (Exception $ex) {
235 return ['message' => $e->getMessage() ?? esc_html__('Please check the authorization details', 'media-cloud-sync'), 'code' => 200, 'success' => false];
236 } catch (Exception $ex) {
237 return ['message' => $ex->getMessage() ?? esc_html__('Please check the authorization details', 'media-cloud-sync'), 'code' => 200, 'success' => false];
238 }
239 }
240
241 /**
242 * isConfigured Function To Identify the congfigurations are correct
243 * @since 1.0.0
244 */
245 public function isConfigured(){
246 if ($this->gcloudClient) {
247 try {
248 $buckets = $this->gcloudClient->buckets();
249 if(!empty($buckets)){
250 foreach($buckets as $bucket) {
251 $name = $bucket->name();
252 if (!empty($name) && $name == $this->bucket_name) {
253 return true;
254 }
255 }
256 }
257 return false;
258 } catch (Exception $ex) {
259 return false;
260 }
261 }
262 return false;
263 }
264
265 /**
266 * Make Object Private
267 * @since 1.0.0
268 *
269 */
270 public function toPrivate($key) {
271 if(!$key) return false;
272
273 $object = $this->bucket->object($key);
274 if ($object->exists()) {
275 $object->update(['acl' => []], ['predefinedAcl' => 'private']);
276 return true;
277 }
278 return false;
279 }
280
281
282 /**
283 * Make Object Public
284 * @since 1.0.0
285 *
286 */
287 public function toPublic($key) {
288 if(!$key) return false;
289
290 $object = $this->bucket->object($key);
291 if ($object->exists()) {
292 $object->update(['acl' => []], ['predefinedAcl' => 'publicRead']);
293 return true;
294 }
295 return false;
296 }
297
298
299 /**
300 * Check the object exist
301 * @since 1.1.8
302 */
303 public function exists($key) {
304 if(!$key) return false;
305
306 $object = $this->bucket->object($key);
307 if ($object->exists()) {
308 return true;
309 }
310
311 return false;
312 }
313
314
315 /**
316 * Upload Single
317 * @since 1.0.0
318 * @return boolean
319 */
320 public function uploadSingle($media_absolute_path, $media_path, $prefix=''){
321 $result = array();
322 if (
323 isset($media_absolute_path) && !empty($media_absolute_path) &&
324 isset($media_path) && !empty($media_path)
325 ) {
326 $file_name = wp_basename( $media_path );
327 if ($file_name) {
328 $upload_path = Utils::generate_object_key($file_name, $prefix);
329
330 // Decide Multipart upload or normal put object
331 if (filesize($media_absolute_path) <= Schema::getConstant('GCLOUD_MULTIPART_MIN_FILE_SIZE')) {
332 // Upload a publicly accessible file. The file size and type are determined by the SDK.
333 try {
334
335 $upload = $this->bucket->upload(
336 fopen($media_absolute_path, 'r'),
337 [
338 'name' => $upload_path,
339 'predefinedAcl' => 'publicRead',
340 ]
341 );
342
343 $object = $this->bucket->object($upload_path);
344
345 if ($object->exists()) {
346 $result = array(
347 'success' => true,
348 'code' => 200,
349 'file_url' => $this->generate_file_url($upload_path),
350 'key' => $upload_path,
351 'message' => esc_html__('File Uploaded Successfully', 'media-cloud-sync'),
352 );
353 } else {
354 $result = array(
355 'success' => false,
356 'code' => 200,
357 'message' => esc_html__('Object not found at server.', 'media-cloud-sync'),
358 );
359 }
360 } catch (Exception $e) {
361 $result = array(
362 'success' => false,
363 'code' => 200,
364 'message' => $e->getMessage(),
365 );
366 }
367 } else {
368 try {
369 $upload = $this->bucket->upload(
370 fopen($media_absolute_path, 'r'),
371 [
372 'name' => $upload_path,
373 'predefinedAcl' => 'publicRead',
374 'chunkSize' => 262144 * 2,
375 ]
376 );
377
378 $object = $this->bucket->object($upload_path);
379
380 if ($object->exists()) {
381 $result = array(
382 'success' => true,
383 'code' => 200,
384 'file_url' => $this->generate_file_url($upload_path),
385 'key' => $upload_path,
386 'message' => esc_html__('File Uploaded Successfully', 'media-cloud-sync'),
387 );
388 } else {
389 $result = array(
390 'success' => false,
391 'code' => 200,
392 'message' => esc_html__('Something happened while uploading to server', 'media-cloud-sync'),
393 );
394 }
395 } catch (Exception $e) {
396 $result = array(
397 'success' => false,
398 'code' => 200,
399 'message' => $e->getMessage(),
400 );
401 }
402 }
403 } else {
404 $result = array(
405 'success' => false,
406 'code' => 200,
407 'message' => esc_html__('Check the file you are trying to upload. Please try again', 'media-cloud-sync'),
408 );
409 }
410 } else {
411 $result = array(
412 'success' => false,
413 'code' => 200,
414 'message' => esc_html__('Insufficient Data. Please try again', 'media-cloud-sync'),
415 );
416 }
417 return $result;
418 }
419
420
421 /**
422 * Save object to server
423 * @since 1.0.0
424 */
425 public function object_to_server($key, $save_path){
426 try {
427 $object = $this->bucket->object($key);
428 if ($object->exists()) {
429 $object->downloadToFile($save_path);
430 if (file_exists($save_path)) {
431 return true;
432 }
433 }
434 } catch (Exception $e) {
435 return false;
436 }
437 return false;
438 }
439
440
441 /**
442 * Delete Single
443 * @since 1.0.0
444 * @return boolean
445 */
446 public function deleteSingle($key){
447 $result = array();
448 if (isset($key) && !empty($key)) {
449 try {
450 $object = $this->bucket->object($key);
451 $object->delete();
452
453 if (!$object->exists()) {
454 $result = array(
455 'success' => true,
456 'code' => 200,
457 'message' => esc_html__('Deleted Successfully', 'media-cloud-sync'),
458 );
459 } else {
460 $result = array(
461 'success' => false,
462 'code' => 200,
463 'message' => esc_html__('File not deleted', 'media-cloud-sync'),
464 );
465 }
466 } catch (Exception $e) {
467 $result = array(
468 'success' => false,
469 'code' => 200,
470 'message' => $e->getMessage(),
471 );
472 }
473 } else {
474 $result = array(
475 'success' => false,
476 'code' => 200,
477 'message' => esc_html__('Insufficient Data. Please try again', 'media-cloud-sync'),
478 );
479 }
480 return $result;
481 }
482
483
484 /**
485 * get presigned URL
486 * @since 1.0.0
487 * @return boolean
488 */
489 public function get_presigned_url($key) {
490 $result = array();
491 if (isset($key) && !empty($key)) {
492 try {
493 $object = $this->bucket->object($key);
494
495 $expires = isset($this->settings['presigned_expire']) ? $this->settings['presigned_expire'] : 20;
496
497 $presignedUrl = $object->signedUrl(new \DateTime(sprintf('+%s minutes', $expires)));
498
499 if ($presignedUrl) {
500 $result = array(
501 'success' => true,
502 'code' => 200,
503 'file_url' => $presignedUrl,
504 'message' => esc_html__('Got Presigned URL Successfully', 'media-cloud-sync'),
505 );
506 } else {
507 $result = array(
508 'success' => false,
509 'code' => 200,
510 'message' => esc_html__('Error getting presigned URL', 'media-cloud-sync'),
511 );
512 }
513 } catch (Exception $e) {
514 $result = array(
515 'success' => false,
516 'code' => 200,
517 'message' => $e->getMessage(),
518 );
519 }
520 } else {
521 $result = array(
522 'success' => false,
523 'code' => 200,
524 'message' => esc_html__('Insufficient Data. Please try again', 'media-cloud-sync'),
525 );
526 }
527 return $result;
528 }
529
530
531 /**
532 * Generate file URL
533 */
534 private function generate_file_url($key){
535 $domain = $this->get_domain();
536
537 return apply_filters('wpmcs_generate_google_file_url',
538 $domain . '/' . $this->bucket_name . '/' . $key,
539 $domain, $key,
540 $this->bucket_name
541 );
542 }
543
544
545 /**
546 * Get domain URL
547 */
548 public function get_domain() {
549 $url_base = 'https://storage.googleapis.com';
550
551 return $url_base;
552 }
553 }