-
Notifications
You must be signed in to change notification settings - Fork 88
/
Copy pathCdnEngine_GoogleDrive.php
849 lines (744 loc) · 24.1 KB
/
CdnEngine_GoogleDrive.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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
<?php
/**
* File: CdnEngine_GoogleDrive.php
*
* @package W3TC
*/
namespace W3TC;
/**
* Class CdnEngine_GoogleDrive
*
* Google drive engine
*
* phpcs:disable PSR2.Classes.PropertyDeclaration.Underscore
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
* phpcs:disable WordPress.PHP.NoSilencedErrors.Discouraged
* phpcs:disable WordPress.PHP.DiscouragedPHPFunctions
* phpcs:disable WordPress.WP.AlternativeFunctions
* phpcs:disable WordPress.DB.DirectDatabaseQuery
* phpcs:disable WordPress.DB.PreparedSQL.NotPrepared
*/
class CdnEngine_GoogleDrive extends CdnEngine_Base {
/**
* Client ID
*
* @var string
*/
private $_client_id;
/**
* Refresh token
*
* @var string
*/
private $_refresh_token;
/**
* Root folder ID
*
* @var string
*/
private $_root_folder_id;
/**
* Root URL
*
* @var string
*/
private $_root_url;
/**
* Google Service Drive object
*
* @var W3TCG_Google_Service_Drive
*/
private $_service;
/**
* Tablename pathmap
*
* @var string
*/
private $_tablename_pathmap;
/**
* Callback function to handle the updated access token.
*
* This callback is invoked with the new access token whenever the token is refreshed.
*
* @var callable
*/
private $_new_access_token_callback;
/**
* Constructor to initialize the Google Drive CDN engine.
*
* @param array $config {
* Configuration options for the Google Drive CDN engine.
*
* @type string $client_id The client ID for the Google Drive API.
* @type string $refresh_token The refresh token for authentication.
* @type string $root_folder_id The root folder ID for the Google Drive.
* @type string $root_url The root URL for the Google Drive CDN.
* @type callable $new_access_token_callback Callback function for new access token.
* @type string $access_token The access token for authentication.
* }
*/
public function __construct( $config = array() ) {
parent::__construct( $config );
$this->_client_id = $config['client_id'];
$this->_refresh_token = $config['refresh_token'];
$this->_root_folder_id = $config['root_folder_id'];
$this->_root_url = rtrim( $config['root_url'], '/' ) . '/';
$this->_new_access_token_callback = $config['new_access_token_callback'];
global $wpdb;
$this->_tablename_pathmap = $wpdb->base_prefix . W3TC_CDN_TABLE_PATHMAP;
try {
$this->_init_service( $config['access_token'] );
} catch ( \Exception $e ) {
$this->_service = null;
}
}
/**
* Initializes the Google Drive service with the provided access token.
*
* @param string $access_token The access token used to authenticate with the Google Drive API.
*
* @throws \Exception If the client ID or access token is missing, or if the service initialization fails.
*/
private function _init_service( $access_token ) {
if ( empty( $this->_client_id ) || empty( $access_token ) ) {
throw new \Exception( \esc_html__( 'Service not configured.', 'w3-total-cache' ) );
}
$client = new \W3TCG_Google_Client();
$client->setClientId( $this->_client_id );
$client->setAccessToken( $access_token );
$this->_service = new \W3TCG_Google_Service_Drive( $client );
}
/**
* Refreshes the access token using the stored refresh token.
*
* @throws \Exception If the refresh request fails or returns an error.
*/
private function _refresh_token() {
$result = wp_remote_post(
W3TC_GOOGLE_DRIVE_AUTHORIZE_URL,
array(
'body' => array(
'client_id' => $this->_client_id,
'refresh_token' => $this->_refresh_token,
),
)
);
if ( is_wp_error( $result ) ) {
throw new \Exception( esc_html( $result ) );
} elseif ( 200 !== (int) $result['response']['code'] ) {
throw new \Exception( wp_kses_post( $result['body'] ) );
}
$access_token = $result['body'];
call_user_func( $this->_new_access_token_callback, $access_token );
$this->_init_service( $access_token );
}
/**
* Uploads files to Google Drive.
*
* @param array $files Array of file descriptors to upload. Each descriptor must contain the 'local_path' and 'remote_path' at a minimum.
* @param array $results Reference to an array where the upload results will be stored.
* @param bool $force_rewrite Whether to forcefully overwrite existing files on Google Drive (default: false).
* @param int $timeout_time Optional timeout time in seconds for the upload operation.
*
* @return bool|string True if the upload was successful, or 'timeout' if the upload timed out.
*/
public function upload( $files, &$results, $force_rewrite = false, $timeout_time = null ) {
if ( is_null( $this->_service ) ) {
return false;
}
$allow_refresh_token = true;
$result = true;
$files_chunks = array_chunk( $files, 20 );
foreach ( $files_chunks as $files_chunk ) {
$r = $this->_upload_chunk(
$files_chunk,
$results,
$force_rewrite,
$timeout_time,
$allow_refresh_token
);
if ( 'refresh_required' === $r ) {
$allow_refresh_token = false;
$this->_refresh_token();
$r = $this->_upload_chunk(
$files_chunk,
$results,
$force_rewrite,
$timeout_time,
$allow_refresh_token
);
}
if ( 'success' !== $r ) {
$result = false;
}
if ( 'timeout' === $r ) {
return 'timeout';
}
}
return $result;
}
/**
* Converts file properties to a Google Drive path.
*
* @param object $file The file object containing properties to convert.
*
* @return string|null The constructed path or null if no valid path properties are found.
*/
private function _properties_to_path( $file ) {
$path_pieces = array();
foreach ( $file->properties as $p ) {
$k = ( 'path' === $p->key ) ? 'path1' : $p->key;
if ( ! preg_match( '/^path[0-9]+$/', $k ) ) {
continue;
}
$path_pieces[ $k ] = $p->value;
}
if ( 0 === count( $path_pieces ) ) {
return null;
}
ksort( $path_pieces );
return join( $path_pieces );
}
/**
* Converts a path string into an array of Google Drive properties.
*
* From google drive api docs:
* Maximum of 124 bytes size per property (including both key and value) string in UTF-8 encoding.
* Maximum of 30 private properties per file from any one application.
*
* @param string $path The path to convert into Google Drive properties.
*
* @return array An array of Google Drive property objects representing the path.
*/
private function _path_to_properties( $path ) {
$chunks = str_split( $path, 55 );
$properties = array();
$i = 1;
foreach ( $chunks as $chunk ) {
$p = new \W3TCG_Google_Service_Drive_Property();
$p->key = 'path' . $i;
$p->value = $chunk;
$properties[] = $p;
++$i;
}
return $properties;
}
/**
* Uploads a chunk of files to Google Drive.
*
* @param array $files Array of file descriptors to upload in the current chunk.
* @param array $results Reference to an array where the upload results will be stored.
* @param bool $force_rewrite Whether to forcefully overwrite existing files on Google Drive.
* @param int $timeout_time Optional timeout time in seconds for the upload operation.
* @param bool $allow_refresh_token Whether to allow refreshing the access token if necessary.
*
* @return string One of the following: 'success', 'timeout', 'refresh_required', or 'with_errors'.
*
* @throws \W3TCG_Google_Auth_Exception If the file update/insert fails.
*/
private function _upload_chunk( $files, &$results, $force_rewrite, $timeout_time, $allow_refresh_token ) {
list( $result, $listed_files ) = $this->list_files_chunk( $files, $allow_refresh_token, $timeout_time );
if ( 'success' !== $result ) {
return $result;
}
$files_by_path = array();
foreach ( $listed_files as $existing_file ) {
$path = $this->_properties_to_path( $existing_file );
if ( $path ) {
$files_by_path[ $path ] = $existing_file;
}
}
// check update date and upload.
foreach ( $files as $file_descriptor ) {
$remote_path = $file_descriptor['remote_path'];
// process at least one item before timeout so that progress goes on.
if ( ! empty( $results ) ) {
if ( ! is_null( $timeout_time ) && time() > $timeout_time ) {
return 'timeout';
}
}
list( $parent_id, $title ) = $this->remote_path_to_title( $file_descriptor['remote_path'] );
$properties = $this->_path_to_properties( $remote_path );
if ( isset( $file_descriptor['content'] ) ) {
// when content specified - just upload.
$content = $file_descriptor['content'];
} else {
$local_path = $file_descriptor['local_path'];
if ( ! file_exists( $local_path ) ) {
$results[] = $this->_get_result(
$local_path,
$remote_path,
W3TC_CDN_RESULT_ERROR,
'Source file not found.',
$file_descriptor
);
continue;
}
$mtime = @filemtime( $local_path );
$p = new \W3TCG_Google_Service_Drive_Property();
$p->key = 'mtime';
$p->value = $mtime;
$properties[] = $p;
if ( ! $force_rewrite && isset( $files_by_path[ $remote_path ] ) ) {
$existing_file = $files_by_path[ $remote_path ];
$existing_size = $existing_file->fileSize; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
$existing_mtime = 0;
if ( is_array( $existing_file->properties ) ) {
foreach ( $existing_file->properties as $p ) {
if ( 'mtime' === $p->key ) {
$existing_mtime = $p->value;
}
}
}
$size = @filesize( $local_path );
if ( $mtime === $existing_mtime && $size === $existing_size ) {
$results[] = $this->_get_result(
$file_descriptor['local_path'],
$remote_path,
W3TC_CDN_RESULT_OK,
'File up-to-date.',
$file_descriptor
);
continue;
}
}
$content = file_get_contents( $local_path );
}
$file = new \W3TCG_Google_Service_Drive_DriveFile();
$file->setTitle( $title );
$file->setProperties( $properties );
$parent = new \W3TCG_Google_Service_Drive_ParentReference();
$parent->setId( $parent_id );
$file->setParents( array( $parent ) );
try {
try {
// update file if there's one already or insert.
if ( isset( $files_by_path[ $remote_path ] ) ) {
$existing_file = $files_by_path[ $remote_path ];
$created_file = $this->_service->files->update(
$existing_file->id,
$file,
array(
'data' => $content,
'uploadType' => 'media',
)
);
} else {
$created_file = $this->_service->files->insert(
$file,
array(
'data' => $content,
'uploadType' => 'media',
)
);
$permission = new \W3TCG_Google_Service_Drive_Permission();
$permission->setValue( '' );
$permission->setType( 'anyone' );
$permission->setRole( 'reader' );
$this->_service->permissions->insert( $created_file->id, $permission );
}
} catch ( \W3TCG_Google_Auth_Exception $e ) {
if ( $allow_refresh_token ) {
return 'refresh_required';
}
throw $e;
}
$results[] = $this->_get_result(
$file_descriptor['local_path'],
$remote_path,
W3TC_CDN_RESULT_OK,
'OK',
$file_descriptor
);
$this->path_set_id( $remote_path, $created_file->id );
} catch ( \W3TCG_Google_Service_Exception $e ) {
$errors = $e->getErrors();
$details = '';
if ( count( $errors ) >= 1 ) {
$details = wp_json_encode( $errors );
}
delete_transient( 'w3tc_cdn_google_drive_folder_ids' );
$results[] = $this->_get_result(
$file_descriptor['local_path'],
$remote_path,
W3TC_CDN_RESULT_ERROR,
'Failed to upload file ' . $remote_path . ' ' . $details,
$file_descriptor
);
$result = 'with_errors';
continue;
} catch ( \Exception $e ) {
delete_transient( 'w3tc_cdn_google_drive_folder_ids' );
$results[] = $this->_get_result(
$file_descriptor['local_path'],
$remote_path,
W3TC_CDN_RESULT_ERROR,
'Failed to upload file ' . $remote_path,
$file_descriptor
);
$result = 'with_errors';
continue;
}
}
return $result;
}
/**
* Deletes specified files from the Google Drive.
*
* This method processes the deletion of multiple files from Google Drive in chunks. It handles token refresh
* if necessary and updates the result of the deletion process.
*
* @param array $files The list of file paths to be deleted.
* @param array $results The array to collect results of each file deletion.
*
* @return bool True on success, false on failure.
*/
public function delete( $files, &$results ) {
$allow_refresh_token = true;
$result = true;
$files_chunks = array_chunk( $files, 20 );
foreach ( $files_chunks as $files_chunk ) {
$r = $this->_delete_chunk( $files_chunk, $results, $allow_refresh_token );
if ( 'refresh_required' === $r ) {
$allow_refresh_token = false;
$this->_refresh_token();
$r = $this->_delete_chunk( $files_chunk, $results, $allow_refresh_token );
}
if ( 'success' !== $r ) {
$result = false;
}
}
return $result;
}
/**
* Deletes a chunk of files from Google Drive.
*
* This method handles the deletion of a chunk of files, processes the API response, and updates the results array.
*
* @param array $files The chunk of file paths to delete.
* @param array $results The array to collect results of each file deletion.
* @param bool $allow_refresh_token Flag to allow refreshing the token if necessary.
*
* @return string One of the following: 'success', 'with_errors', or 'refresh_required'.
*/
private function _delete_chunk( $files, &$results, $allow_refresh_token ) {
list( $result, $listed_files ) = $this->list_files_chunk( $files, $allow_refresh_token );
if ( 'success' !== $result ) {
return $result;
}
foreach ( $listed_files->items as $item ) {
try {
$this->_service->files->delete( $item->id );
$results[] = $this->_get_result(
$item->title,
$item->title,
W3TC_CDN_RESULT_OK,
'OK'
);
} catch ( \Exception $e ) {
$results[] = $this->_get_result(
'',
'',
W3TC_CDN_RESULT_ERROR,
'Failed to delete file ' . $item->title
);
$result = 'with_errors';
continue;
}
}
return $result;
}
/**
* Lists a chunk of files based on the provided file descriptors.
*
* This method lists files matching the specified descriptors, checking if the refresh token is required or if a
* timeout occurred.
*
* @param array $files The file descriptors to list.
* @param bool $allow_refresh_token Flag to allow refreshing the token if necessary.
* @param int|null $timeout_time The timeout time, if any.
*
* @return array Array containing the result status and the listed files.
*
* @throws \W3TCG_Google_Auth_Exception Throws an exception if authentication fails or the listFiles call fails.
*/
private function list_files_chunk( $files, $allow_refresh_token, $timeout_time = null ) {
$titles_filter = array();
try {
foreach ( $files as $file_descriptor ) {
list( $parent_id, $title ) = $this->remote_path_to_title( $file_descriptor['remote_path'] );
$titles_filter[] = '("' . $parent_id . '" in parents and title = "' . $title . '")';
if ( ! is_null( $timeout_time ) && time() > $timeout_time ) {
return array( 'timeout', array() );
}
}
} catch ( \W3TCG_Google_Auth_Exception $e ) {
if ( $allow_refresh_token ) {
return array( 'refresh_required', array() );
}
throw $e;
} catch ( \Exception $e ) {
return array( 'with_errors', array() );
}
// find files.
try {
try {
$listed_files = $this->_service->files->listFiles(
array( 'q' => '(' . join( ' or ', $titles_filter ) . ') and trashed = false' )
);
} catch ( \W3TCG_Google_Auth_Exception $e ) {
if ( $allow_refresh_token ) {
return array( 'refresh_required', array() );
}
throw $e;
}
} catch ( \Exception $e ) {
return array( 'with_errors', array() );
}
return array( 'success', $listed_files );
}
/**
* Converts a remote file path to its title and parent ID.
*
* This method extracts the title and parent folder ID from a remote file path.
*
* @param string $remote_path The remote file path.
*
* @return array An array containing the parent ID and file title.
*/
private function remote_path_to_title( $remote_path ) {
$title = substr( $remote_path, 1 );
$pos = strrpos( $remote_path, '/' );
if ( false === $pos ) {
$path = '';
$title = $remote_path;
} else {
$path = substr( $remote_path, 0, $pos );
$title = substr( $remote_path, $pos + 1 );
}
$title = str_replace( '"', "'", $title );
$parent_id = $this->path_to_parent_id( $this->_root_folder_id, $path );
return array( $parent_id, $title );
}
/**
* Resolves the parent folder ID for a given path.
*
* This method recursively resolves the parent folder ID for a given path within the Google Drive hierarchy.
*
* @param string $root_id The root folder ID.
* @param string $path The folder path to resolve.
*
* @return string The resolved parent folder ID.
*/
private function path_to_parent_id( $root_id, $path ) {
if ( empty( $path ) ) {
return $root_id;
}
$path = ltrim( $path, '/' );
$pos = strpos( $path, '/' );
if ( false === $pos ) {
$top_folder = $path;
$remaining_path = '';
} else {
$top_folder = substr( $path, 0, $pos );
$remaining_path = substr( $path, $pos + 1 );
}
$new_root_id = $this->parent_id_resolve_step( $root_id, $top_folder );
return $this->path_to_parent_id( $new_root_id, $remaining_path );
}
/**
* Resolves the folder ID for a given folder within a parent folder.
*
* This method checks if the folder exists, creates it if necessary, and resolves its ID.
*
* @param string $root_id The parent folder ID.
* @param string $folder The folder name.
*
* @return string The resolved folder ID.
*/
private function parent_id_resolve_step( $root_id, $folder ) {
// decode top folder.
$ids_string = get_transient( 'w3tc_cdn_google_drive_folder_ids' );
$ids = @unserialize( $ids_string );
if ( isset( $ids[ $root_id . '_' . $folder ] ) ) {
return $ids[ $root_id . '_' . $folder ];
}
// find folder.
$items = $this->_service->files->listFiles(
array(
'q' => '"' . $root_id . '" in parents and title = "' . $folder . '" and mimeType = "application/vnd.google-apps.folder" and trashed = false',
)
);
if ( count( $items ) > 0 ) {
$id = $items[0]->id;
} else {
// create folder.
$file = new \W3TCG_Google_Service_Drive_DriveFile(
array(
'title' => $folder,
'mimeType' => 'application/vnd.google-apps.folder',
)
);
$parent = new \W3TCG_Google_Service_Drive_ParentReference();
$parent->setId( $root_id );
$file->setParents( array( $parent ) );
$created_file = $this->_service->files->insert( $file );
$id = $created_file->id;
$permission = new \W3TCG_Google_Service_Drive_Permission();
$permission->setValue( '' );
$permission->setType( 'anyone' );
$permission->setRole( 'reader' );
$this->_service->permissions->insert( $id, $permission );
}
if ( ! is_array( $ids ) ) {
$ids = array();
}
$ids[ $root_id . '_' . $folder ] = $id;
set_transient( 'w3tc_cdn_google_drive_folder_ids', serialize( $ids ) );
return $id;
}
/**
* Runs a test by uploading and then deleting a test file on Google Drive.
*
* This method uploads a test file, and if successful, deletes it, returning an error if either operation fails.
*
* @param string $error The variable to store error messages if any operation fails.
*
* @return bool True on success, false on failure.
*/
public function test( &$error ) {
$test_content = '' . wp_rand();
$file = array(
'local_path' => 'n/a',
'remote_path' => '/folder/test.txt',
'content' => $test_content,
);
$results = array();
if ( ! $this->upload( array( $file ), $results ) ) {
$error = sprintf( 'Unable to upload file %s', $file['remote_path'] );
return false;
}
if ( ! $this->delete( array( $file ), $results ) ) {
$error = sprintf( 'Unable to delete file %s', $file['remote_path'] );
return false;
}
return true;
}
/**
* Returns the domains supported by the Google Drive CDN.
*
* This method returns an empty array since the current implementation does not support specific domains.
*
* @return array An empty array.
*/
public function get_domains() {
return array();
}
/**
* Returns the type of headers supported by the CDN.
*
* This method returns a constant indicating that no custom headers are supported.
*
* @return string One of the constants indicating header support (e.g., `W3TC_CDN_HEADER_NONE`).
*/
public function headers_support() {
return W3TC_CDN_HEADER_NONE;
}
/**
* Purges all cached files from the Google Drive CDN.
*
* This method does not support purging all cached files and will always return false.
*
* @param array $results The array to collect results of the purging operation.
*
* @return bool Always returns false.
*/
public function purge_all( &$results ) {
return false;
}
/**
* Sets the remote ID for a given file path.
*
* This method stores the remote ID associated with a file path in the database.
*
* @param string $path The local file path.
* @param string $id The remote file ID.
*
* @return void
*/
private function path_set_id( $path, $id ) {
global $wpdb;
$md5 = md5( $path );
if ( ! $id ) {
$sql = "INSERT INTO $this->_tablename_pathmap
(path, path_hash, remote_id)
VALUES (%s, %s, NULL)
ON DUPLICATE KEY UPDATE remote_id = NULL";
$wpdb->query( $wpdb->prepare( $sql, $path, $md5 ) );
} else {
$sql = "INSERT INTO $this->_tablename_pathmap
(path, path_hash, remote_id)
VALUES (%s, %s, %s)
ON DUPLICATE KEY UPDATE remote_id = %s";
$wpdb->query( $wpdb->prepare( $sql, $path, $md5, $id, $id ) );
}
}
/**
* Gets the remote ID associated with a file path.
*
* This method retrieves the remote ID for a file path, either from the database or by querying Google Drive.
*
* @param string $path The local file path.
* @param bool $allow_refresh_token Flag to allow refreshing the token if necessary.
*
* @return string|null The remote file ID or null if not found.
*
* @throws \W3TCG_Google_Auth_Exception Throws an exception if authentication fails or the listFiles call fails.
*/
private function path_get_id( $path, $allow_refresh_token = true ) {
global $wpdb;
$md5 = md5( $path );
$sql = "SELECT remote_id FROM $this->_tablename_pathmap WHERE path_hash = %s";
$query = $wpdb->prepare( $sql, $md5 );
$results = $wpdb->get_results( $query );
if ( count( $results ) > 0 ) {
return $results[0]->remote_id;
}
$props = $this->_path_to_properties( $path );
$q = 'trashed = false';
foreach ( $props as $prop ) {
$key = $prop->key;
$value = str_replace( "'", "\\'", $prop->value );
$q .= " and properties has { key='$key' and value='$value' and visibility='PRIVATE' }";
}
try {
$items = $this->_service->files->listFiles( array( 'q' => $q ) );
} catch ( \W3TCG_Google_Auth_Exception $e ) {
if ( $allow_refresh_token ) {
$this->_refresh_token();
return $this->path_get_id( $path, false );
}
throw $e;
}
$id = ( 0 === count( $items ) ) ? null : $items[0]->id;
$this->path_set_id( $path, $id );
return $id;
}
/**
* Formats a URL for accessing a file on Google Drive.
*
* This method returns a URL to access a file on Google Drive based on its remote ID.
*
* @param string $path The local file path.
* @param bool $allow_refresh_token Flag to allow refreshing the token if necessary.
*
* @return string|null The formatted URL or null if the ID could not be retrieved.
*/
public function format_url( $path, $allow_refresh_token = true ) {
$id = $this->path_get_id( Util_Environment::remove_query( $path ) );
if ( is_null( $id ) ) {
return null;
}
return 'https://drive.google.com/uc?id=' . $id;
}
}